How to Create GraphQL APIs With ASP.Net Core for Beginners

How to Create GraphQL APIs With ASP.Net Core for Beginners
Table of Contents

An improved and more versatile query language for APIs than REST is called GraphQL. Originally developed by Facebook, it is now open-sourced and supported by a sizable community.

Over the past few years, restful architecture has emerged as the industry standard for designing online APIs. REST APIs, however, have proven to be too rigid to adapt to the ever-changing needs of the clients using them. Hire .Net core developers to implement and integrate GraphQl dotNet core. Now let us understand in this blog what is GraphQL and how to build a GraphQL server with ASP.NET Core.

What is GraphQL?

A Query language for APIs called GraphQL allows the client to dictate the response it receives, rather than the server dictating how to respond.

It answers the client’s inquiry by acting as a mediator between the client and creating a GraphQL backend service. Multiple resource requests can be combined into a single GraphQL Query formatter.

GraphQL was created to address the demand for greater flexibility and efficiency and to address many of the drawbacks and inefficiencies that developers have when working with REST APIs. Therefore, GraphQL is just an improved REST.

When performing CRUD operations on an entity using REST, we typically have numerous endpoints. Additionally, there are issues with overfetching and underfetching, and the returned data structures are fixed and rather rigid.

  • When endpoints deliver more data than what is required in the user interface, this is known as overfetching.
  • When a particular endpoint doesn’t supply enough of the necessary data, it’s referred to as underfetching. The client will need to place another call to get what it requires.

Considering TechEvent as a whole for example: A participant may register for more than one tech event, and events may have many participants. To retrieve the necessary data in REST, you must contact three endpoints here: 

  • GET/API/techEvents => To obtain all tech events
  • GET/techEvents/API/{id} => To get single ID
  • GET/API/techEvents/{id}/participants => to gather information on attendees at an event

However, using GraphQL, we can archive this data required with a single endpoint POST/GraphQL rather than three separate endpoints, and we can accomplish this by simply changing the query as seen below.

{ "query": "query{ event(eventId:1){ eventId speaker } }"
}
{ "query": "query{ events{ eventId eventName participants{ participantName phone } } }"
}

GraphQL vs REST API

To determine their respective purposes, let’s examine some similarities and differences between GraphQL and REST APIs.

In REST

  • https://localhost:7025/employees?id=2 is the straightforward query endpoint.
  • What information is returned as a response is determined by the server?
  • To retrieve more than one resource, you must use multiple API endpoints; for example, you cannot retrieve departmental and employee data via an API call.
  • Because HTTP GET in REST has a well-defined caching behavior that is used by web servers, CDNs, proxies, and browsers, it is simple to cache the answer.
  • No specific library is needed to use REST APIs.

In GraphQL:

  • The complex Query- https://localhost:7025/graphql?query={employee(id:2){name,deptName}} 
  • Customers choose which information to receive back in response.
  • Permit the fusion of several resource requests into a single API call. For example, https://localhost:7025/graphql?query={employee(id:2){name,deptName}, department(id:1){deptName}}. The department with department id = 1 and the employee with id = 2 are the outcomes of this API query.
  • It also enables caching, albeit the query behavior makes it more difficult.
  • More robust tools are needed for both the client and server sides. This might not be appropriate for straightforward CRUD tasks.
Building GraphQL APIs with ASP.Net Core

Building GraphQL APIs with ASP.Net Core

Customers choose which information to receive back in response. Let’s look at an example of implementing dotNet core GraphQL API in ASP.NET Core.

The need to create APIs to query employees and their departments is the stated problem. There won’t be any database connections because I’m hardcoding the data and keeping the API minimal for demo purposes.

We would start by creating an ASP.NET Core web API project and proceeding as described below.

  1. Required Conditions

Make sure the following is installed on your machine before we begin:

  • .NET Core SDK
  • Visual Studio Code, or any other code editor of choice
  • For testing the API, use Postman.
  1. Organizing the project

Make a new project for the ASP.NET Core Web API first. Using your chosen terminal, type the following command to accomplish this:

GraphQLDemo, a new WebAPI for DotNet

The ‘GraphQLDemo’ ASP.NET Core Web API project is created with this command. Go to the project directory and navigate:

cd GraphQLDemo

  1. Adding the Required Libraries for GraphQL

We need to include the required libraries to use GraphQL in our project. Execute the subsequent command:

Add package HotChocolate to dotnet.ASPNetCore

Add package HotChocolate to dotnet.Microsoft.Net Core. Playground

  1. Select a Model

Describe the model. Make a class named EmployeeModel.cs and include the following code in it.

public record Employee(int Id, string Name, int Age, int DeptId ); public record Department(int Id, string Name); public class EmployeeDetails { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } public string DeptName { get; set; } } public class EmployeeDetailsType: ObjectGraphType<EmployeeDetails> { public EmployeeDetailsType() { Field(x => x.Id); Field(x => x.Name); Field(x => x.Age); Field(x => x.DeptName); } }
Since GraphQL is unable to comprehend EmployeeDetails, which is the model for API responses, we must develop a mapping. To that end, we create the EmployeeDetailsType Field mapping class.

5. Create the Employee Service class to handle the information derived from the data source. In this instance, we hardcode. Add the following code to the EmployeeService.cs class after creating it.

public interface IEmployeeService { public List<EmployeeDetails> GetEmployees(); public List<EmployeeDetails> GetEmployee(int empId); public List<EmployeeDetails> GetEmployeesByDepartment(int deptId); } public class EmployeeService : IEmployeeService { public EmployeeService() { } private List<Employee> employees = new List<Employee> { new Employee(1, "Tom", 25, 1), new Employee(2, "Henry", 28, 1), new Employee(3, "Steve", 30, 2), new Employee(4, "Ben", 26, 2), new Employee(5, "John", 35, 3), }; private List<Department> departments = new List<Department> { new Department(1, "IT"), new Department(2, "Finance"), new Department(3, "HR"), }; public List<EmployeeDetails> GetEmployees() { return employees.Select(emp => new EmployeeDetails { Id = emp.Id, Name = emp.Name, Age = emp.Age, DeptName = departments.First(d => d.Id == emp.DeptId).Name, }).ToList(); } public List<EmployeeDetails> GetEmployee(int empId) { return employees.Where(emp => emp.Id == empId).Select(emp => new EmployeeDetails { Id = emp.Id, Name = emp.Name, Age = emp.Age, DeptName = departments.First(d => d.Id == emp.DeptId).Name, }).ToList(); } public List<EmployeeDetails> GetEmployeesByDepartment(int deptId) { return employees.Where(emp => emp.DeptId == deptId).Select(emp => new EmployeeDetails { Id = emp.Id, Name = emp.Name, Age = emp.Age, DeptName = departments.First(d => d.Id == deptId).Name, }).ToList(); } }

6. The GraphQL Query, which is essential for GraphQL APIs, will be create here. To a class called EmployeeQuery.cs, add the following code.

public class EmployeeQuery : ObjectGraphType { public EmployeeQuery(IEmployeeService employeeService) { Field<ListGraphType<EmployeeDetailsType>>(Name = "Employees", resolve : x => employeeService.GetEmployees()); Field<ListGraphType<EmployeeDetailsType>>(Name = "Employee", arguments: new QueryArguments(new QueryArgument<IntGraphType> { Name = "id"}), resolve: x => employeeService.GetEmployee(x.GetArgument<int>("id"))); } } public class EmployeeDetailsSchema : Schema { public EmployeeDetailsSchema(IServiceProvider serviceProvider) : base(serviceProvider) { Query = serviceProvider.GetRequiredService<EmployeeQuery>(); } }

Here, we take two actions: First, to retrieve data, we develop a GraphQL Query (also known as EmployeeQuery) mapping against our EmployeeService functions. The format is as follows:

FieldListGraphTypeclass modelmapping type>(Name, reasons, and conclusion);

If they are not require, arguments are optional.

Two query mappings have been defined in the code above to retrieve all workers as well as employees with employee IDs.

The second step involves building a class called EmployeeDetailsSchema that derives from Schema to translate the Employee query (EmployeeQuery) class to the GraphQL schema.

7. In the Program.cs class, register the types and services, including GraphQL, to the dependency container.

builder.Services.AddSingleton<IEmployeeService, EmployeeService>();
builder.Services.AddSingleton<EmployeeDetailsType>();
builder.Services.AddSingleton<EmployeeQuery>();
builder.Services.AddSingleton<ISchema, EmployeeDetailsSchema>();
builder.Services.AddGraphQL(b => b .AddAutoSchema<EmployeeQuery>() // schema .AddSystemTextJson()); // serializer

We will register the GraphQL endpoint and playground-which functions similarly to Swagger-with the application as the final step.

app.UseGraphQL<ISchema>("/graphql"); // url to host GraphQL endpoint
app.UseGraphQLPlayground( "/", // url to host Playground at new GraphQL.Server.Ui.Playground.PlaygroundOptions { GraphQLEndPoint = "/graphql", // url of GraphQL endpoint SubscriptionsEndPoint = "/graphql", // url of GraphQL endpoint });

Now we run the final step for the application.

The entire code used in this example is available at this link.

In case you wish to compare the REST API and GraphQL API code side by side, this also includes the WEB API integration services and implementation of the same endpoints that we covered above.

How Can I Set up an Azure Application Gateways Graphql API?

  1. Go to the Azure portal and check the API Management.
  2. From the menu on the left, choose APIs > + Add API.
  3. Go to Define a new API and click on the GraphQL symbol.
  4. Choose “Create.”
  5. Navigate through or edit the schema on the Design tab once the API has been built.

Conclusion

That’s how you use ASP.NET Core to develop a GraphQL API. You may learn more about how to utilize ASP.NET Core and GraphQL together to construct effective APIs. For more information, visit our website or collaborate with CMARIX if you’re searching for .Net core development services.

Written by Parth Patel

Parth Patel is a Microsoft Certified Solution Associate (MCSA) and DotNet Team Lead at CMARIX, a leading ASP.NET MVC Development Company. With 10+ years of extensive experience in developing enterprise grade custom softwares. Parth has been actively working on different business domains like Banking, Insurance, Fintech, Security, Healthcare etc to provide technology services.

Looking for Microsoft Software Development Services?
Follow ON Google News
Read by 513
Quick Look

Related Blogs

How To Create a SharePoint Site: Step-by-Step Guide

How To Create a SharePoint Site: Step-by-Step Guide

An improved and more versatile query language for APIs than REST is […]

10 Best Azure Security Tools and its Features in 2025

10 Best Azure Security Tools and its Features in 2025

An improved and more versatile query language for APIs than REST is […]

A Guide to Harness Azure AI Services For Your Business

A Guide to Harness Azure AI Services For Your Business

An improved and more versatile query language for APIs than REST is […]

Hello.
Have an Interesting Project?
Let's talk about that!