Public Transport Tracking App Development – A Complete Guide in 2024
.NET For Enterprise App Development – A Guide for App Development
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.
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.
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:
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 } } }" }
To determine their respective purposes, let’s examine some similarities and differences between GraphQL and REST APIs.
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.
Make sure the following is installed on your machine before we begin:
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
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
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.
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.
An improved and more versatile query language for APIs than REST is […]