GraphQl API Client Integration In ASP.NET Core 3.1

This project integrated the GraphQL API 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 response payload are defined on the client-side.

let us start,

First, create a .net core 3.1 web API project. For integrating GraphQL API 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 GraphQL API 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 get the GraphqlHttpClient we can create GraphqlClientBase class, That looks like

public abstract class GraphqlClientBase    
{    
    public readonly GraphQLHttpClient _graphQLHttpClient ;    
    public GraphqlClientBase()    
    {    
        if(_graphQLHttpClient == null)    
        {    
            _graphQLHttpClient = GetGraphQlApiClient();    
        }    
    }    
  
    public GraphQLHttpClient GetGraphQlApiClient()    
    {    
         //initialize graphql endpoint eg:https://testproject1.hasura.app/v1/graphql
        var endpoint = "********";    
  
        var httpClientOption = new GraphQLHttpClientOptions    
        {    
            EndPoint = new Uri(endpoint)    
        };    
  
       return new GraphQLHttpClient(httpClientOption, new NewtonsoftJsonSerializer());    
    }     
}

we can inherit this class wherever we need the HttpClient.

The NewtonsoftJsonSerializer class is in 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 on how to do query and mutation to GraphQL via GraphqlApiClient, For that, we can create service contract ITransferService

public interface ITransferService  
{  
    Task<IEnumerable<TransferDto>> GetTransfers();  
}

The actual implementation is given below

public class TransferService : GraphqlClientBase, ITransferService    
{    
    public async Task<IEnumerable<TransferDto>> GetTransfers()    
    {    
        var query = @"query MyQuery {    
                                      Transfers {    
                                        id    
                                        description
                                        title    
                                      }    
                                    }";    
    
        var request = new GraphQLRequest(query);    
            
    
        var response = await _graphQLHttpClient.SendQueryAsync<TransferQueryResponse>(request);    
        return response.Data.Transfer;    
    }    
}

where TransferDto and TransferQueryResponse are model classes

public class TransferQueryResponse  
{  
    public IEnumerable<TransferDto> Transfer { get; set; }  
}  
  
public class TransferDto  
{  
    public int Id { get; set; }
    public string Title { get; set; }  
    public string Description{ get; set; }
}

The GraphqlHttpClient class have method SendQueryAsync which is responsible for fetching data(query) from GraphQL database.

Similarly GraphqlHttpClient class has method for Mutation (modifying data) is SendMutationAsync.

The GraphQLRequest object stores the query and variables for the correponding GraphQL query/ mutation action.

To call this GetTransfers() method we can create a Controller TransferController

[Route("api/[controller]")]    
[ApiController]    
public class TransferController : ControllerBase    
{    
    private readonly ITransferService _transferService;    
  
    public TransferController(ITransferService transferService)    
    {    
        _transferService = transferService;    
    }    
    [HttpGet, Route("get-all")]    
    public async Task<IActionResult> GetTransfer()    
    {    
        try    
        {    
            var transfers = await _transferService.GetTransfers();    
            return Ok(transfers.OrderBy(s => s.Id));    
        }    
        catch (Exception ex)    
        {    
            throw ex;    
        }    
    }    
} 

also we need to register Dependencies in the ConfigureService method in Startup.cs

public void ConfigureServices(IServiceCollection services)    
{    
    services.AddScoped<ITransferService, TransferService>(); //add this line   
    services.AddControllers();    
}  

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 GraphQL API.

Sample output:

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

Thanks