Build an API in .NET Core with GraphQL
Tags: graphql, dotnetcore, dotnet
Published: 2020-07-24 07:53:56

**[GraphQL](https://graphql.org/)** is a query language for APIs which provides a more efficient and flexible alternative to REST. It was originally built by Facebook but now it’s open-sourced.

To designing web APIs, Restful architecture has become the standard over couple of years. However, REST APIs have shown to be too inflexible to keep up with the rapidly changing requirements of the clients that access them.

To solve many of the shortcomings and inefficiencies that developers experience when interacting with REST APIs, GraphQL was developed to cope with the need for more flexibility and efficiency. So, **GraphQL is nothing but a better REST.**

In REST, we generally have multiple endpoints to perform CRUD operations on an entity and also there are over fetching and under fetching problems and it’s return fixed data structures which is little inflexible in nature.

_**Overfetching** means endpoints return additional information that’s not needed in the UI._

_**Underfetching** means that a specific endpoint doesn’t provide enough of the required information. The client will have to make additional call to fetch everything it need._

Let’s consider Tech Event as an entity - A tech event can have multiple participants and similarly a participant can enroll to multiple tech events.
Here you need to call 3 endpoints to fetch the required data in REST.
1. GET/api/techEvents => To get all tech events
2. GET/api/techEvent/{id} => To get single tech event info by id
3. GET/api/techEvent/{id}/participants => To get participants details for an event

But using GraphQL, a single endpoint **POST/graphql** will be sufficient to archive this data requirement instead of 3 different endpoints and we can do it by just modifying the query as like below.
```JSON
{   
 "query":  
  "query{  
     event(eventId:1){  
       eventId   
       speaker  
     }  
   }"  
}
```

```JSON
{   
 "query":  
  "query{  
     events{  
       eventId  
       eventName  
       participants{  
            participantName  
            phone  
        }  
     }  
   }"  
}
```
Below Illustration on Rest API vs GraphQL with respect to endpoints:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ex7dm6jiztrwqt7vgaha.jpg)

### Implementation of GraphQL with ASP.NET Core:
In this post, we're going to build a GraphQL server from scratch. The server will expose TechEvent management graphQL endpoint which will allow querying on data.

For demo purpose, let’s create a local DB called “TechEventDB” in MS SQL server (or you can use UseInMemoryDatabase) and add below tables with some dummy data:
1. Table - _TechEventInfo_: This table consists of technical event information like event id , name , speaker etc.
2. Table - _Participant_: This table consists of participant information like name, phone email etc.
3. Table - _EventParticipants_: This is a mapping table b/w event and participants with many to many relationships.
```SQL
CREATE TABLE dbo.TechEventInfo(    
    EventId int IDENTITY(1,1) NOT NULL,    
    EventName varchar(100) NOT NULL,    
    Speaker varchar(100) NOT NULL,    
    EventDate Date NULL  
 CONSTRAINT [PK_TechEventInfo] PRIMARY KEY CLUSTERED     
(    
    EventId ASC    
)  
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]    
) ON [PRIMARY] 
```
```SQL
CREATE TABLE dbo.Participant(    
    ParticipantId int IDENTITY(1,1) NOT NULL,    
    ParticipantName varchar(100) NOT NULL,    
    Email varchar(100) NOT NULL,    
    Phone varchar(20) NULL,  
 CONSTRAINT [PK_Participant] PRIMARY KEY CLUSTERED     
(    
    ParticipantId ASC    
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]    
) ON [PRIMARY]  
```
```SQL
CREATE TABLE [dbo].EventParticipants  
(  
    EventParticipantId INT NOT NULL IDENTITY(1,1) ,  
        EventId INT NOT NULL,  
    ParticipantId INT NULL,  
    CONSTRAINT [PK_EventParticipants] PRIMARY KEY CLUSTERED  
    (  
        EventParticipantId ASC  
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)   
    ON [PRIMARY]  
,CONSTRAINT [FK_EventParticipants_TechEventInfo_EventId] FOREIGN KEY (EventId) REFERENCES [TechEventInfo] (EventId)   
,CONSTRAINT [FK_EventParticipants_Participant_ParticipantId] FOREIGN KEY ([ParticipantId]) REFERENCES [Participant] ([ParticipantId])   
) ON [PRIMARY]  
```
Now we have to insert some sample data into all the tables. 
Once we done with this steps, let's create ASP.NET core WebAPI project called “GraphQL.API” and add DB connection string in appsettings.json.
```C#
"ConnectionStrings": {  
    "GraphQLDBConnection": "Server=Local-PC\\SQLEXPRESS;Database=TechEventDB;Trusted_Connection=True;MultipleActiveResultSets=true"  
  }
```
Add the DbContext under ConfigureServices in Startup.cs
```C#
services.AddDbContext<TechEventDBContext>  
                (options => options.UseSqlServer(Configuration.GetConnectionString("GraphQLDBConnection")));
``` 
To generate entity context class, now we need to run scaffold command from package manager console (Tools => Nuget Package Manager => Package Manager Console) to generate dbContext class using Entity Framework Core. Create folder called Infrastructure and sub folder called DBContext into the project.
`Scaffold-DbContext “Server=Local-PC\SQLEXPRESS;Database=TechEventDB;Trusted_Connection=True;” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Infrastructure\DBContext`
After successful execution of Scaffold command, entity and context will be added as like below.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/b8gu1f32pm7rey4aczme.png)
Now create Repositories folder where we can handle CRUD operation on tech event entity.

_ITechEventRepository.cs_
```C#
using GraphQL.API.Infrastructure.DBContext;  
using System.Collections.Generic;  
using System.Threading.Tasks;  
  
namespace GraphQL.API.Infrastructure.Repositories  
{  
    public interface ITechEventRepository  
    {  
        Task<TechEventInfo[]> GetTechEvents();  
        Task<TechEventInfo> GetTechEventById(int id);  
        Task<List<Participant>> GetParticipantInfoByEventId(int id);  
    }  
}  
```
_TechEventRepository.cs_
```C#
using GraphQL.API.Infrastructure.DBContext;  
using Microsoft.EntityFrameworkCore;  
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
using GraphQL.API.Domain;  
  
  
namespace GraphQL.API.Infrastructure.Repositories  
{  
    /// <summary>  
    /// TechEventRepository.  
    /// </summary>  
    public class TechEventRepository : ITechEventRepository  
    {  
  
        /// <summary>  
        /// The _context.  
        /// </summary>  
        private readonly TechEventDBContext _context;  
  
        public TechEventRepository(TechEventDBContext context)  
        {  
            this._context = context;  
        }  
  
        public async Task<List<Participant>> GetParticipantInfoByEventId(int id)  
        {  
            return await(from ep in this._context.EventParticipants  
                                 join p in this._context.Participant on ep.ParticipantId equals p.ParticipantId  
                                 where ep.EventId == id  
                                 select p).ToListAsync();  
        }  
  
        public async Task<TechEventInfo> GetTechEventById(int id)  
        {  
            return await Task.FromResult( _context.TechEventInfo.FirstOrDefault(i => i.EventId == id));  
        }  
  
        public async Task<TechEventInfo[]> GetTechEvents()  
        {  
            return _context.TechEventInfo.ToArray();  
        }  
    }  
}  
```
Register DI on Startup.cs for Repository:
```C#
services.AddTransient<ITechEventRepository, TechEventRepository>();  
```
So far, we've created our db context and repository. It's time to start using GraphQL integration in our project, so that we can get our GraphQL server running.

Add below Nuget packages into API project:
```XML
<PackageReference Include="GraphQL" Version="2.4.0" />  
<PackageReference Include="graphiql" Version="1.2.0" />  
<PackageReference Include="GraphQL.Server.Transports.AspNetCore" Version="3.4.0" />
```
First we're going to configure the GraphQL schema step by step as mention below:

   Step 1: **Create GraphQL types** - To admit through our endpoint to our GraphQL clients.

   Step 2: **Create a GraphQL query object** - To allow us to define the queries that will then surface to the clients which they can then issue against our endpoint.

   Step 3: **Create schema object to expose the query** - To allow tools like graphical to inspect and see what types are available. It's also necessary to enable GraphQL clients.

   Step 4: **Register all types in Startup.cs** - To register all of those types with our asp.net core IOC container.

Add a folder into project called “GraphqlCore” – where we will keep GraphQL related Type , Schema , Query files etc.

##### Create GraphQL types
Create TechEventInfoType.cs which inherits from ObjectGraphType<TechEventInfo> and set all the fields into the constructor.
* _ObjectGraphType <T>_: Used to expose GraphQL types in our schema, “T” here is model.
* _ListGraphType <T>_: Used to define GraphQL Collection.

_TechEventInfoType.cs_
```C#
using GraphQL.API.Infrastructure.DBContext;  
using GraphQL.API.Infrastructure.Repositories;  
using GraphQL.Types;  
  
namespace GraphQL.API.GraphqlCore  
{  
    public class TechEventInfoType : ObjectGraphType<TechEventInfo>  
    {  
        public TechEventInfoType(ITechEventRepository repository)  
        {  
            Field(x => x.EventId).Description("Event id.");  
            Field(x => x.EventName).Description("Event name.");  
            Field(x => x.Speaker).Description("Speaker name.");  
            Field(x => x.EventDate).Description("Event date.");  
  
            Field<ListGraphType<ParticipantType>>(  
              "participants",  
              arguments: new QueryArguments(new QueryArgument<IntGraphType> { Name = "eventId" }),  
              resolve: context => repository.GetParticipantInfoByEventId(context.Source.EventId)  
           );  
        }  
    }
}
```
Here, Field() is nothing but used to expose to client If you have any specific domain property and that you don’t want to expose – don’t need to add into constructor. Also, we can set description of each field. Those descriptions will actually populate back to the client when they use graphical and they view the schema.

In this TechEventInfoType, we added Field called “participants” as we want to expose participants along with events and Field will be like Field<ListGraphType<ParticipantType>> (Name, Arguments, Resolve Func)

Name (i.e. “participants”) is basically name of the field. Arguments (e.g. “eventId”) is nothing but used as input to resolver function. Resolve function is going to get invoked in GetParticipantInfoByEventId() to retrieve participants from repository.

Similarly, for Participants we need to create ParticipantType.cs.
```C#
using GraphQL.API.Infrastructure.DBContext;  
using GraphQL.Types;  
  
namespace GraphQL.API.GraphqlCore  
{  
    public class ParticipantType : ObjectGraphType<Participant>  
    {  
        public ParticipantType()  
        {  
            Field(x => x.ParticipantId).Description("Participant id.");  
            Field(x => x.ParticipantName).Description("Participant name.");  
            Field(x => x.Email).Description("Participant Email address.");  
            Field(x => x.Phone).Description("Participant phone number.");  
        }  
    }  
}  
```
##### Create a GraphQL query object

Now we're going to create our query which will be exposed to client.
1. Return a TechEventInfo based on Id.
2. Return a list of TechEventInfo.

Here, ObjectGraphType<object> we're just going to put object and that's because we don't have an existing class that we're mapping to.

_TechEventQuery.cs_
```C#
using GraphQL.API.Infrastructure.Repositories;  
using GraphQL.Types;  
   
namespace GraphQL.API.GraphqlCore  
{  
    public class TechEventQuery : ObjectGraphType<object>  
    {  
        public TechEventQuery(ITechEventRepository repository)  
        {  
            Name = "TechEventQuery";  
  
            Field<TechEventInfoType>(  
               "event",  
               arguments: new QueryArguments(new QueryArgument<IntGraphType> { Name = "eventId" }),  
               resolve: context => repository.GetTechEventById(context.GetArgument<int>("eventId"))  
            );  
  
            Field<ListGraphType<TechEventInfoType>>(  
             "events",  
             resolve: context => repository.GetTechEvents()  
          );  
        }  
    }  
}
```
##### Create schema object to expose the query

Schema will be used to resolve the query. We will resolve the previously created query; i.e., TechEventQuery.cs and dependency resolver is going to be necessary in order for dependency injection to work.

_TechEventSchema.cs_
```C#
using GraphQL.Types;  
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
  
namespace GraphQL.API.GraphqlCore  
{  
    public class TechEventSchema : Schema  
    {  
        public TechEventSchema(IDependencyResolver resolver)  
        {  
            Query = resolver.Resolve<TechEventQuery>();  
            DependencyResolver = resolver;  
        }  
  
    }  
}
```
##### Register all types in Startup.cs

Now start registering the types, query and Schema that we created so far. To do this, Add the below code snippet under configureservices in startup.cs. 
```C#
services.AddSingleton<TechEventInfoType>();  
services.AddSingleton<ParticipantType>();  
services.AddSingleton<TechEventQuery>();  
var sp = services.BuildServiceProvider();  
services.AddSingleton<ISchema>(new TechEventSchema(new FuncDependencyResolver(type => sp.GetService(type))));  
```
Then before the app.UseMvc(); add the following line in configure method :
```C#
app.UseGraphiQl("/graphql");  
```
#####Web API Controller

You can now create a GraphQLController with a single action method/endpoint that handles every incoming query that our schema supports. The client will always be sending the POST request which will contain the query name, operation name, and the variables. You can create a new class called GraphqlQuery.cs that will serve as a model for all queries from the client.

_GraphqlQuery.cs_
```C#
using Newtonsoft.Json.Linq;  
  
namespace GraphQL.API.GraphqlCore  
{  
  public class GraphqlQuery  
    {  
    public string OperationName { get; set; }  
    public string NamedQuery { get; set; }  
    public string Query { get; set; }  
    public JObject Variables { get; set; }  
  }  
}
```
_GraphQLController.cs_
```C#
using System.Threading.Tasks;  
using GraphQL.API.GraphqlCore;  
using GraphQL.Types;  
using Microsoft.AspNetCore.Mvc;  
  
  
namespace GraphQL.API.Controllers  
{  
    [Route("[controller]")]  
    [ApiController]  
    public class GraphQLController : ControllerBase  
    {  
        private readonly IDocumentExecuter _documentExecuter;  
        private readonly ISchema _schema;  
        public GraphQLController(ISchema schema, IDocumentExecuter documentExecuter)  
        {  
            _schema = schema;  
            _documentExecuter = documentExecuter;  
        }  
  
        [HttpPost]  
        public async Task<IActionResult> PostAsync([FromBody] GraphqlQuery query)  
        {  
            if (query == null) { throw new ArgumentNullException(nameof(query)); }  
            var inputs = query.Variables.ToInputs();  
            var executionOptions = new ExecutionOptions  
            {  
                Schema = _schema,  
                Query = query.Query,  
                Inputs = inputs  
            };  
  
            var result = await _documentExecuter.ExecuteAsync(executionOptions);  
  
            if (result.Errors?.Count > 0)  
            {  
                return BadRequest(result);  
            }  
  
            return Ok(result);  
        }  
    }  
}
```
Add below in startup.cs
```C#
services.AddSingleton<IDocumentExecuter, DocumentExecuter>();  
```
In REST, as a rule, we use the HTTP GET verb to fetch data. In GraphQL we can certainly still use GET requests for fetching data however that means we must store our "query" in the query string of the URL ie. api/graphql?query=.... A cleaner approach is to send the query in the JSON-encoded body of a POST request.

At the starting stage, we added a NuGet package called GraphiQL which will provide the UI where we can write our GraphQL queries and at the same time, we can see the result. For that, we need to browse the graphql path. We can configure the same at the launch of the browser.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/h4mtgfmsbr2iytcwksqp.png)
Now we are done with demo project, let’s see overall folder and file structure of it:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/n78t5ors75ytva5o1did.png)
Now we are ready to run our demo application and test GraphQL query. Once it’s loaded in browser, you will see below **GraphiQL** screen. On the left side, we have a query input section and at the right side, the result section. You can see query schema on Document Explorer section. On left top section, you will play button to execute your query.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/v1zxka7eakc68z9uwe0q.png)
>GraphiQL an in-browser IDE for exploring GraphQL. GraphiQL features include: Syntax highlighting Intelligent type ahead of fields, arguments, types, and more. Real-time error highlighting and reporting. Automatic query completion.

#### Test GraphQL Query:

To get event details with participants by event id , you can write below query.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/jwdzdayl4392cnfsqdhk.png)
Similarly, to get participant name for each event:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/cp0nzsqirb8ckdgetpjr.png)
Whatever data you need from Techevent entity, you can easily get it without modifying any code or adding addition endpoints - which resolved over fetching and under fetching problem in REST.
We can test the same GraphQL API using postman tool. Below screenshot for your reference.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/q9wnc3g1sagv4eum3cgj.png)
Till now we discussed on GraphQL query, in next post we will talk about Mutation which is nothing but modifying the data.
 
### Conclusion: 

I hope this post has helped you gain some insight into GraphQL. It’s too flexible, isn’t it? It can provide developer to building and delivering data-rich APIs over REST. Last but not the least, there is a misconception around GraphQL is that being a database technology. GraphQL is a query language for APIs - not databases.

**Finally , all the code demonstrated here can be found in the [GitHub](https://github.com/dynamicanupam/AspNetCoreWithGraphQL).**