{"id":37773,"date":"2024-06-07T11:54:12","date_gmt":"2024-06-07T11:54:12","guid":{"rendered":"https:\/\/www.cmarix.com\/blog\/?p=37773"},"modified":"2026-04-09T13:11:49","modified_gmt":"2026-04-09T13:11:49","slug":"how-to-create-graphql-apis-with-asp-net-core","status":"publish","type":"post","link":"https:\/\/www.cmarix.com\/blog\/how-to-create-graphql-apis-with-asp-net-core\/","title":{"rendered":"How to Create GraphQL APIs With ASP.Net Core for Beginners"},"content":{"rendered":"\n<p>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.<\/p>\n\n\n\n<p>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. <a href=\"https:\/\/www.cmarix.com\/hire-dotnet-core-developers.html\">Hire .Net core developers<\/a> 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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What is GraphQL?<\/h2>\n\n\n\n<p>A Query language for APIs called GraphQL allows the client to dictate the response it receives, rather than the server dictating how to respond.<\/p>\n\n\n\n<p>It answers the client&#8217;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.<\/p>\n\n\n\n<p>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 <a href=\"https:\/\/www.cmarix.com\/blog\/how-to-ensure-rest-api-security\/\">REST APIs<\/a>. Therefore, GraphQL is just an improved REST.<\/p>\n\n\n\n<p>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.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>When endpoints deliver more data than what is required in the user interface, this is known as overfetching.<\/li>\n\n\n\n<li>When a particular endpoint doesn&#8217;t supply enough of the necessary data, it&#8217;s referred to as underfetching. The client will need to place another call to get what it requires.<\/li>\n<\/ul>\n\n\n\n<p>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:&nbsp;<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>GET\/API\/techEvents =&gt; To obtain all tech events<\/li>\n\n\n\n<li>GET\/techEvents\/API\/{id} =&gt; To get single ID<\/li>\n\n\n\n<li>GET\/API\/techEvents\/{id}\/participants =&gt; to gather information on attendees at an event<\/li>\n<\/ul>\n\n\n\n<p>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.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{       \n \"query\":      \n  \"query{      \n     event(eventId:1){      \n       eventId       \n       speaker      \n     }      \n   }\"      \n}     \n{     \n \"query\":    \n  \"query{    \n     events{    \n       eventId    \n       eventName    \n       participants{    \n            participantName    \n            phone\n        }\n     }\n   }\"\n}\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">GraphQL vs REST API<\/h2>\n\n\n\n<p>To determine their respective purposes, let&#8217;s examine some similarities and differences between GraphQL and REST APIs.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">In REST<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>https:\/\/localhost:7025\/employees?id=2 is the straightforward query endpoint.<\/li>\n\n\n\n<li>What information is returned as a response is determined by the server?<\/li>\n\n\n\n<li>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.<\/li>\n\n\n\n<li>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.<\/li>\n\n\n\n<li>No specific library is needed to use REST APIs.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">In GraphQL:<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The complex Query- https:\/\/localhost:7025\/graphql?query={employee(id:2){name,deptName}}\u00a0<\/li>\n\n\n\n<li>Customers choose which information to receive back in response.<\/li>\n\n\n\n<li>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.<\/li>\n\n\n\n<li>It also enables caching, albeit the query behavior makes it more difficult.<\/li>\n\n\n\n<li>More robust tools are needed for both the client and server sides. This might not be appropriate for straightforward CRUD tasks.<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image size-full\"><a href=\"https:\/\/www.cmarix.com\/inquiry.html\"><img decoding=\"async\" width=\"951\" height=\"271\" src=\"https:\/\/www.cmarix.com\/blog\/wp-content\/uploads\/2024\/06\/build-graphql-apis-with-aspnet-core.webp\" alt=\"Building GraphQL APIs with ASP.Net Core\" class=\"wp-image-37776\" srcset=\"https:\/\/www.cmarix.com\/blog\/wp-content\/uploads\/2024\/06\/build-graphql-apis-with-aspnet-core.webp 951w, https:\/\/www.cmarix.com\/blog\/wp-content\/uploads\/2024\/06\/build-graphql-apis-with-aspnet-core-400x114.webp 400w, https:\/\/www.cmarix.com\/blog\/wp-content\/uploads\/2024\/06\/build-graphql-apis-with-aspnet-core-768x219.webp 768w\" sizes=\"(max-width: 951px) 100vw, 951px\" \/><\/a><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Building GraphQL APIs with ASP.Net Core<\/h2>\n\n\n\n<p>Customers choose which information to receive back in response. Let&#8217;s look at an example of implementing dotNet core GraphQL API in ASP.NET Core.<\/p>\n\n\n\n<p>The need to create APIs to query employees and their departments is the stated problem. There won&#8217;t be any database connections because I&#8217;m hardcoding the data and keeping the API minimal for demo purposes.<\/p>\n\n\n\n<p>We would start by creating an ASP.NET Core web API project and proceeding as described below.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Required Conditions<\/strong><\/li>\n<\/ol>\n\n\n\n<p>Make sure the following is installed on your machine before we begin:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>.NET Core SDK<\/li>\n\n\n\n<li>Visual Studio Code, or any other code editor of choice<\/li>\n\n\n\n<li>For testing the API, use Postman.<\/li>\n<\/ul>\n\n\n\n<ol class=\"wp-block-list\" start=\"2\">\n<li><strong>Organizing the project<\/strong><\/li>\n<\/ol>\n\n\n\n<p>Make a new project for the ASP.NET Core Web API first. Using your chosen terminal, type the following command to accomplish this:<\/p>\n\n\n\n<p>GraphQLDemo, a new WebAPI for DotNet<\/p>\n\n\n\n<p>The &#8216;GraphQLDemo&#8217; ASP.NET Core Web API project is created with this command. Go to the project directory and navigate:<\/p>\n\n\n\n<p>cd GraphQLDemo<\/p>\n\n\n\n<ol class=\"wp-block-list\" start=\"3\">\n<li><strong>Adding the Required Libraries for GraphQL<\/strong><\/li>\n<\/ol>\n\n\n\n<p>We need to include the required libraries to use GraphQL in our project. Execute the subsequent command:<\/p>\n\n\n\n<p>Add package HotChocolate to dotnet.ASPNetCore<\/p>\n\n\n\n<p>Add package HotChocolate to dotnet.Microsoft.Net Core. Playground<\/p>\n\n\n\n<ol class=\"wp-block-list\" start=\"4\">\n<li><strong>Select a Model<\/strong><\/li>\n<\/ol>\n\n\n\n<p>Describe the model. Make a class named EmployeeModel.cs and include the following code in it.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public record Employee(int Id, string Name, int Age, int DeptId );\n\n   public record Department(int Id, string Name);\n\n   public class EmployeeDetails\n   {\n       public int Id { get; set; }\n       public string Name { get; set; }\n       public int Age { get; set; }\n       public string DeptName { get; set; }\n   }\n\n   public class EmployeeDetailsType: ObjectGraphType&lt;EmployeeDetails&gt;\n   {\n       public EmployeeDetailsType()\n       {\n           Field(x =&gt; x.Id);\n           Field(x =&gt; x.Name);\n           Field(x =&gt; x.Age);\n           Field(x =&gt; x.DeptName);\n       }\n   }\n\nSince 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.<\/code><\/pre>\n\n\n\n<p><strong>5. Create the Employee Service class<\/strong> 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.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public interface IEmployeeService\n   {\n       public List&lt;EmployeeDetails&gt; GetEmployees();\n\n       public List&lt;EmployeeDetails&gt; GetEmployee(int empId);\n\n       public List&lt;EmployeeDetails&gt; GetEmployeesByDepartment(int deptId);\n   }\n\n   public class EmployeeService : IEmployeeService\n   {\n       public EmployeeService()\n       {\n\n       }\n       private List&lt;Employee&gt; employees = new List&lt;Employee&gt;\n       {\n           new Employee(1, \"Tom\", 25, 1),\n           new Employee(2, \"Henry\", 28, 1),\n           new Employee(3, \"Steve\", 30, 2),\n           new Employee(4, \"Ben\", 26, 2),\n           new Employee(5, \"John\", 35, 3),\n\n       };\n\n       private List&lt;Department&gt; departments = new List&lt;Department&gt;\n       {\n           new Department(1, \"IT\"),\n           new Department(2, \"Finance\"),\n           new Department(3, \"HR\"),\n       };\n\n       public List&lt;EmployeeDetails&gt; GetEmployees()\n       {\n           return employees.Select(emp =&gt; new EmployeeDetails {\n               Id = emp.Id,\n               Name = emp.Name,\n               Age = emp.Age,\n               DeptName = departments.First(d =&gt; d.Id == emp.DeptId).Name,\n           }).ToList();\n          \n       }\n       public List&lt;EmployeeDetails&gt; GetEmployee(int empId)\n       {\n           return employees.Where(emp =&gt; emp.Id == empId).Select(emp =&gt; new EmployeeDetails\n           {\n               Id = emp.Id,\n               Name = emp.Name,\n               Age = emp.Age,\n               DeptName = departments.First(d =&gt; d.Id == emp.DeptId).Name,\n           }).ToList();\n       }\n\n       public List&lt;EmployeeDetails&gt; GetEmployeesByDepartment(int deptId)\n       {\n           return employees.Where(emp =&gt; emp.DeptId == deptId).Select(emp =&gt; new EmployeeDetails\n           {\n               Id = emp.Id,\n               Name = emp.Name,\n               Age = emp.Age,\n               DeptName = departments.First(d =&gt; d.Id == deptId).Name,\n           }).ToList();\n       }\n   }<\/code><\/pre>\n\n\n\n<p><strong>6. The GraphQL Query, which is essential for GraphQL APIs, will be create here. To a class called EmployeeQuery.cs, add the following code.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class EmployeeQuery : ObjectGraphType\n   {\n       public EmployeeQuery(IEmployeeService employeeService) {\n           Field&lt;ListGraphType&lt;EmployeeDetailsType&gt;&gt;(Name = \"Employees\", resolve : x =&gt; employeeService.GetEmployees());\n           Field&lt;ListGraphType&lt;EmployeeDetailsType&gt;&gt;(Name = \"Employee\",\n               arguments: new QueryArguments(new QueryArgument&lt;IntGraphType&gt; { Name = \"id\"}),\n               resolve: x =&gt; employeeService.GetEmployee(x.GetArgument&lt;int&gt;(\"id\")));\n       }\n   }\n\n   public class EmployeeDetailsSchema : Schema\n   {\n       public EmployeeDetailsSchema(IServiceProvider serviceProvider) : base(serviceProvider) {\n           Query = serviceProvider.GetRequiredService&lt;EmployeeQuery&gt;();\n       }\n   }\n<\/code><\/pre>\n\n\n\n<p>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:<\/p>\n\n\n\n<p>FieldListGraphTypeclass modelmapping type&gt;(Name, reasons, and conclusion);<\/p>\n\n\n\n<p>If they are not require, arguments are optional.<\/p>\n\n\n\n<p>Two query mappings have been defined in the code above to retrieve all workers as well as employees with employee IDs.<\/p>\n\n\n\n<p>The second step involves building a class called EmployeeDetailsSchema that derives from Schema to translate the Employee query (EmployeeQuery) class to the GraphQL schema.<\/p>\n\n\n<div class=\"linkedSection\">\n\t\t\t\t<i class=\"linkedIcon\"><\/i>\n\t\t\t\t<div class=\"linkedHead\">You may like this: <a href=\"https:\/\/www.cmarix.com\/blog\/graphql-the-future-of-enterprise-software-and-api-development\/\">GraphQL: The Future of Enterprise Software and API Development<br \/>\n<\/a><\/div>\n\t\t\t<\/div>\n\n\n\n<p><strong>7. In the Program.cs class, register the types and services, including GraphQL, to the dependency container.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>builder.Services.AddSingleton&lt;IEmployeeService, EmployeeService&gt;();\nbuilder.Services.AddSingleton&lt;EmployeeDetailsType&gt;();\nbuilder.Services.AddSingleton&lt;EmployeeQuery&gt;();\nbuilder.Services.AddSingleton&lt;ISchema, EmployeeDetailsSchema&gt;();\nbuilder.Services.AddGraphQL(b =&gt; b\n   .AddAutoSchema&lt;EmployeeQuery&gt;()  \/\/ schema\n   .AddSystemTextJson());   \/\/ serializer<\/code><\/pre>\n\n\n\n<p>We will register the GraphQL endpoint and playground-which functions similarly to Swagger-with the application as the final step.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>app.UseGraphQL&lt;ISchema&gt;(\"\/graphql\");            \/\/ url to host GraphQL endpoint\napp.UseGraphQLPlayground(\n    \"\/\",                               \/\/ url to host Playground at\n    new GraphQL.Server.Ui.Playground.PlaygroundOptions\n    {\n        GraphQLEndPoint = \"\/graphql\",         \/\/ url of GraphQL endpoint\n        SubscriptionsEndPoint = \"\/graphql\",   \/\/ url of GraphQL endpoint\n    });\n<\/code><\/pre>\n\n\n\n<p>Now we run the final step for the application.<\/p>\n\n\n\n<p>The entire code used in this example is available at this <a href=\"https:\/\/github.com\/binodmahto\/FunProjects\/tree\/main\/GraphQL\/graphqlapidemo\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">link<\/a>.<\/p>\n\n\n\n<p>In case you wish to compare the REST API and GraphQL API code side by side, this also includes the WEB <a href=\"https:\/\/www.cmarix.com\/api-integration.html\">API integration services<\/a> and implementation of the same endpoints that we covered above.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How Can I Set up an Azure Application Gateways Graphql API?<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Go to the Azure portal and check the API Management.<\/li>\n\n\n\n<li>From the menu on the left, choose APIs &gt; + Add API.<\/li>\n\n\n\n<li>Go to Define a new API and click on the GraphQL symbol.<\/li>\n\n\n\n<li>Choose &#8220;Create.&#8221;<\/li>\n\n\n\n<li>Navigate through or edit the schema on the Design tab once the API has been built.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>That&#8217;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, <a href=\"https:\/\/www.cmarix.com\/inquiry.html\">visit our website<\/a> or collaborate with CMARIX if you&#8217;re searching for <a href=\"https:\/\/www.cmarix.com\/asp-net-core-development.html\">.Net core development services<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>An improved and more versatile query language for APIs than REST is [&hellip;]<\/p>\n","protected":false},"author":8,"featured_media":37777,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[10490],"tags":[],"class_list":["post-37773","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-asp-net-core"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.cmarix.com\/blog\/wp-json\/wp\/v2\/posts\/37773","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.cmarix.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.cmarix.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.cmarix.com\/blog\/wp-json\/wp\/v2\/users\/8"}],"replies":[{"embeddable":true,"href":"https:\/\/www.cmarix.com\/blog\/wp-json\/wp\/v2\/comments?post=37773"}],"version-history":[{"count":22,"href":"https:\/\/www.cmarix.com\/blog\/wp-json\/wp\/v2\/posts\/37773\/revisions"}],"predecessor-version":[{"id":37798,"href":"https:\/\/www.cmarix.com\/blog\/wp-json\/wp\/v2\/posts\/37773\/revisions\/37798"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.cmarix.com\/blog\/wp-json\/wp\/v2\/media\/37777"}],"wp:attachment":[{"href":"https:\/\/www.cmarix.com\/blog\/wp-json\/wp\/v2\/media?parent=37773"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.cmarix.com\/blog\/wp-json\/wp\/v2\/categories?post=37773"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.cmarix.com\/blog\/wp-json\/wp\/v2\/tags?post=37773"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}