GraphQl API Client Integration In ASP.NET Core 3.1

This project integrated the GraphqlApi client in .net core 3.1. Before going to implementation we need to know what is graphql.
 
GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.
 
By simply means, in graphql the request payload and reponse payload are defined on the client side.
 
let us start,
 
First create a .net core 3.1 webapi project. For integrating graphqlapi client we need to install two nuget packages that are,
  • GraphQL.Client (version 3.2.1)
  • GraphQL.Client.Serializer.Newtonsoft (version 3.2.1)
For creating graphqlApi project i have used Hasura graphql which very powerful tool for creating graphql api backend..To know more about hasura check https://hasura.io/

To getting the GraphqlHttpClient we can create GraphqlClientBase class, That looks like
  1. public abstract class GraphqlClientBase    
  2. {    
  3.     public readonly GraphQLHttpClient _graphQLHttpClient ;    
  4.     public GraphqlClientBase()    
  5.     {    
  6.         if(_graphQLHttpClient == null)    
  7.         {    
  8.             _graphQLHttpClient = GetGraphQlApiClient();    
  9.         }    
  10.     }    
  11.   
  12.     public GraphQLHttpClient GetGraphQlApiClient()    
  13.     {    
  14.         var endpoint = "https://testproject1.hasura.app/v1/graphql";    
  15.   
  16.         var httpClientOption = new GraphQLHttpClientOptions    
  17.         {    
  18.             EndPoint = new Uri(endpoint)    
  19.         };    
  20.   
  21.        return new GraphQLHttpClient(httpClientOption, new NewtonsoftJsonSerializer());    
  22.     }     
  23. } 
we can inherit this class wherever we need the HttpClient.
 
The NewtonsoftJsonSerializer class is in the GraphQL.Client.Serializer.Newtonsoft Library
 
There are 3 core concepts in graphql that are
  • Query - fetch data from corresponding data source
  • Mutation - update/modify data
  • Subscription - To watch/monitor data
In this blog we are focusing how to do query and mutation to graphql via GraphqlApiClient, For that we can create service contract ITransferService
  1. public interface ITransferService  
  2. {  
  3.     Task<IEnumerable<TransferDto>> GetTransfers();  
  4. }  
The actual implementation is given below
  1. public class TransferService : GraphqlClientBase, ITransferService    
  2. {    
  3.     public async Task<IEnumerable<TransferDto>> GetTransfers()    
  4.     {    
  5.         var query = @"query MyQuery {    
  6.                                       Transfer {    
  7.                                         Id    
  8.                                         destinationTenantId    
  9.                                         originTenantId    
  10.                                         originalManuscriptId    
  11.                                         title    
  12.                                       }    
  13.                                     }";    
  14.     
  15.         var request = new GraphQLRequest(query);    
  16.             
  17.     
  18.         var response = await _graphQLHttpClient.SendQueryAsync<TransferQueryResponse>(request);    
  19.         return response.Data.Transfer;    
  20.     }    
  21. }  
where TransferDto and TransferQueryResponse are model classes
  1. public class TransferQueryResponse  
  2. {  
  3.     public IEnumerable<TransferDto> Transfer { getset; }  
  4. }  
  5.   
  6. public class TransferDto  
  7. {  
  8.     public int Id { getset; }  
  9.     public int OriginalManuscriptId { getset; }  
  10.     public string Title { getset; }  
  11.     public string OriginTenantId { getset; }  
  12.     public string DestinationTenantId { getset; }  
  13. }  
The GraphqlHttpClient class have method SendQueryAsync which is responsible for fetch data(query) from graphql database.
 
Similarly GraphqlHttpClient class have method for Mutation (modifying data) is SendMutationAsync.
 
The GraphQLRequest object stores the query and variables for the correponding graphlql query/ mutation action.
 
To call this GetTransfers() method we can create a Controller TransferController
  1. [Route("api/[controller]")]    
  2. [ApiController]    
  3. public class TransferController : ControllerBase    
  4. {    
  5.     private readonly ITransferService _transferService;    
  6.   
  7.     public TransferController(ITransferService transferService)    
  8.     {    
  9.         _transferService = transferService;    
  10.     }    
  11.     [HttpGet, Route("get-all")]    
  12.     public async Task<IActionResult> GetTransfer()    
  13.     {    
  14.         try    
  15.         {    
  16.             var transfers = await _transferService.GetTransfers();    
  17.             return Ok(transfers.OrderBy(s => s.Id));    
  18.         }    
  19.         catch (Exception ex)    
  20.         {    
  21.             throw ex;    
  22.         }    
  23.     }    
  24. } 
also we need to register Dependencies in the ConfigureService method in Startup.cs
  1. public void ConfigureServices(IServiceCollection services)    
  2. {    
  3.     services.AddScoped<ITransferService, TransferService>(); //add this line   
  4.     services.AddControllers();    
  5. }   
back after doing all this code, we can run project by pressing f5 or Debug=> Start Debugging in the menu bar when we call the https://localhost:{your_port}/api/transfer/get-all. we will get all the data via graphqlapi
 
GraphQl Api client Integration in Asp.net core 3.1

Github project url: https://github.com/SarathBaiju/Graphql-Api-Client-in-.net-core-3.1
 
Thanks

Next Recommended Reading Model Popup In ASP.NET Core 3.1