Why use GraphQL in Web API?
Let’s first understand why we use GraphQL when we directly expose data through a Web API endpoint. Consider a scenario where you want to create endpoints for the User Entity. So, you can expose APIs like GetAllUsers, GetUsersByUserId, and GetUserByUserName to return limited fields like UserName and UserId, not the entire User entity. So again, you need to expose other endpoints, and ultimately, we will end up with n number of endpoints, which is very difficult to maintain. GraphQL helps us here as it’s a schema-definition language. You need to expose only one endpoint, which is expected to be the GraphQL query, and you can get your desired results with a single endpoint.
Step-by-Step Implementation of GraphQL in Web API
Let’s see step by step implementation of GraphQL in Web API.
Create an ASP.NET Core web application and select API as the template and Core 2.0 as the version.
In our demo, we need GraphQL as well as Entity Framework Core, so add the NuGet Packages mentioned below.
- GraphQL
- GraphQL.Server.Transports.AspnetCore
- GraphQL.Server.UI.Playground
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.Tools
- Microsoft.VisualStudio.Web.CodeGeneration.Design
Database Setup
Now, let’s create a database using the MS SQL Server for our demo purposes. Also, create a table and add some dummy data. You can execute the script below to create a table with the data inside the GraphQLDemo database.
USE [GraphQLDemo]
GO
/****** Object: Table [dbo].[Employee] Script Date: 2/2/2019 9:15:36 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Employee](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[Name] [varchar](100) NULL,
[Email] [varchar](50) NULL,
[Mobile] [varchar](50) NULL,
[Company] [varchar](100) NULL,
[Address] [varchar](100) NULL,
[ShortDescription] [varchar](1000) NULL,
[LongDescription] [text] NULL,
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[Employee] ON
GO
INSERT [dbo].[Employee] ([Id], [Name], [Email], [Mobile], [Company], [Address], [ShortDescription], [LongDescription]) VALUES (1, N'Akshay', N'[email protected]', N'9999999999', N'Dotnetbees', N'Hyderabad', N'Short Description', N'Long Description')
GO
INSERT [dbo].[Employee] ([Id], [Name], [Email], [Mobile], [Company], [Address], [ShortDescription], [LongDescription]) VALUES (2, N'Panth', N'[email protected]', N'8888888888', N'Radix', N'Vadodara', N'SD', N'LD')
GO
SET IDENTITY_INSERT [dbo].[Employee] OFF
GO
Connection String Setup
In the next step, we need a connection string to connect with the database. So, as a normal practice, let’s store our connection string in Appsettings.json.
Appsettings.json
"ConnectionStrings": {
"DefaultConnection": "Server=akshay-pc\\devsql2016;Database=GraphQLDemo;Trusted_Connection=True;MultipleActiveResultSets=true"
}
Scaffold Database
Run the scaffold command to generate the model and dbcontext class.
Open the Package Manager Console and execute the below command.
Scaffold-DbContext “Server=AKSHAY-PC\DEVSQL2016;Database=GraphQLDemo;Trusted_Connection=True;” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models.
Employee.cs
namespace GraphQLInWebApiCore
{
public partial class Employee
{
public long Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public string Company { get; set; }
public string Address { get; set; }
public string ShortDescription { get; set; }
public string LongDescription { get; set; }
}
}
GraphQLDemoContext
using Microsoft.EntityFrameworkCore;
namespace GraphQLInWebApiCore
{
public partial class GraphQLDemoContext : DbContext
{
public GraphQLDemoContext()
{
}
public GraphQLDemoContext(DbContextOptions<GraphQLDemoContext> options)
: base(options)
{
}
public virtual DbSet<Employee> Employee { get; set; }
}
}
DbContext configuration
Add the DbContext under ConfigureServices in Startup.cs, which adds to the service collection and can be injected whenever required.
Startup.cs
services.AddDbContext<GraphQLDemoContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
Create Employee Repository
Create an employee repository to get all the employees from the database through dbcontext, i.e., Entity Framework Core.
IEmployeeRepository.cs
using System.Collections.Generic;
using System.Threading.Tasks;
namespace GraphQLInWebApiCore
{
public interface IEmployeeRepository
{
Task<List<Employee>> GetEmployees();
}
}
EmployeeRepository.cs
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GraphQLInWebApiCore
{
public class EmployeeRepository : IEmployeeRepository
{
private readonly GraphQLDemoContext _context;
public EmployeeRepository(GraphQLDemoContext context)
{
_context = context;
}
public Task<List<Employee>> GetEmployees()
{
return _context.Employee.ToListAsync();
}
}
}
So far, we are done with
- Creating a table in DB
- Adding sample data to the table
- Configuring Entity Framework Core and setting the connection with a database
- Creating a repository that will return the list of employees
Implement GraphQL Types
Let’s start implementing GraphQL. This requires Schema, Query, and ObjectGraphType.









Jaydeep PatilPosted Sep 14, 2022, 6:19 PM
Great content
Thung QPosted Apr 14, 2020, 1:07 PM
Great post that helps me familiar with GraphQL. I just want to update to anyone stuck in API sector because now (15/4/2020), graphql-dotnet repo has updated, replaced GraphQLClient with GraphQLHttpClient plus an JSON serializer of its own (though it implement from Newtonsoft). You can graphql-dotnet repo in the link: https://github.com/graphql-dotnet/graphql-client. The PostAsync replaced by SendQueryAsync.
kaushal dhoraPosted Apr 2, 2020, 8:30 AM
Hello Akshay, Good post it helps me to intiatal setup for the GraphQL. I do have one query. In my database there are multiple Schema like dbo.[Table] and [locator].[TableName], how can I deal with such a scenario.
Sdy AlorPosted Jul 22, 2019, 1:51 AM
Thank you <3
Mihai SaceleanPosted Jun 25, 2019, 8:27 AM
The download link is dead! When I clicked on it the following error message appeared: This site can’t be reached The webpage at https://www.c-sharpcorner.com/AdRedirector.aspx?AdId=133&target=https://www.e-iceblue.com/download/free-products.html?aff_id=100 might be temporarily down or it may have moved permanently to a new web address.ERR_FAILED
Ano MepaniPosted Feb 25, 2019, 7:12 AM
Good start with GraphQL which is widely used as Data Layer. How to use this API Endpoint or consume API from browser using jQuery Ajax or fetch API?
Former memberPosted Feb 23, 2019, 10:19 AM
One more series...good.