Some more advanced GraphQL concepts with HotChocolate - Part 2

In this post, we provide a concise overview of GraphQL, outlining its core principles and functionalities. Additionally, we guide readers through the process of setting up their development environment using Visual Studio.

What is GraphQL ?

GraphQL emerged from Facebook's development efforts in the early 2010s with the primary objective of optimizing data transmission over networks, particularly for mobile applications where bandwidth efficiency was crucial. Subsequently, it was formalized as a specification that servers must adhere to in order to fulfill the contractual requirements. This flexible approach allows GraphQL servers to be implemented in virtually any programming language, and it's not uncommon to find multiple implementations in the same language.

Very important

It's essential to underscore that GraphQL solely serves as a SPECIFICATION. Consequently, APIs leveraging this technology necessitate deployment on servers that conform to this specification and possess the ability to comprehend and fulfill requests crafted in the corresponding language. In practice, a GraphQL server is typically instantiated through the installation of a library or a runtime environment tailored for GraphQL implementation.

HotChocolate serves as an illustration of a C# implementation of the GraphQL specification.

For more details, please refer here: Building GraphQL API with HotChocolate

What is HotChocolate ?

HotChocolate is an open-source GraphQL server for the Microsoft .NET platform that is compliant with the newest GraphQL October 2021 spec + Drafts, which makes Hot Chocolate compatible to all GraphQL compliant clients.
https://chillicream.com/docs/hotchocolate/v13

We'll set up a basic GraphQL server using HotChocolate in an Azure Function, and then we'll query it with JavaScript.

Creating the environment

  • Create a new solution named EOCS.GraphQLAdvanced for example and a new Azure Functions project in it.

  • Create a new class named Customer.cs and add the following code to it.

1public class Customer
2{
3    public string Id { get; set; }
4
5    public string Name { get; set; }
6
7    public int Age { get; set; }
8}
  • Create a new interface named ICustomerRepository and add the following code in it.
1public interface ICustomerRepository
2{
3    List<Customer> GetAllCustomers();
4    Customer GetCustomerById(string id);
5}
  • Create a new class named MockCustomerRepository that implements the ICustomerRepository interface.
 1public class MockCustomerRepository : ICustomerRepository
 2{
 3    public List<Customer> GetAllCustomers()
 4    {
 5        return new List<Customer>()
 6        {
 7            new Customer(){ Id = "0001", Name = "Bruce Smith", Age = 45 },
 8            new Customer(){ Id = "0010", Name = "Melissa Price", Age = 52 }
 9        };
10    }
11	
12    public Customer GetCustomerById(string id)
13    {
14        return new Customer(){ Id = "0001", Name = "Bruce Smith", Age = 45 };
15    }
16}
  • Add the HotChocolate.AzureFunctions NuGet package.

  • Create a class named CustomerService.cs (or a more general name) and add the following code to it.

 1public class CustomerService
 2{
 3    private readonly IGraphQLRequestExecutor _executor;
 4
 5    public CustomerService(IGraphQLRequestExecutor executor)
 6    {
 7        _executor = executor;
 8    }
 9
10    [FunctionName(nameof(Run))]
11    public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "graphql/{**slug}")] HttpRequest req)
12    {
13        return await _executor.ExecuteAsync(req);
14    }
15}
  • Create a class named StartUp.cs to bootstrap the Azure Function.
 1public class StartUp : FunctionsStartup
 2{
 3    public override void Configure(IFunctionsHostBuilder builder)
 4    {
 5        ConfigureServices(builder.Services);
 6    }
 7
 8    private static void ConfigureServices(IServiceCollection services)
 9    {
10        services.AddSingleton<ICustomerRepository, MockCustomerRepository>();
11    }
12}
Very important

This setup is currently non-functional; it merely establishes the framework for future development.

Consuming the service

Now it's time to consume our service, and for this, we will create a simple HTML file.

  • Create a new ASP.NET Core Web App project, name it EOCS.GraphQLAdvanced.Client for example and add a file named indexQuery.html in wwwroot.

  • Add the following code to it.

 1<html>
 2<head>
 3    <title>GraphQL</title>
 4</head>
 5<body>
 6    <pre><code class="language-json" id="code"></code></pre>
 7    <script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.14.9/beautify.min.js"></script>
 8    
 9</body>
10</html>
  • Edit the Program.cs code.
 1public class Program
 2{
 3    public static void Main(string[] args)
 4    {
 5        var builder = WebApplication.CreateBuilder(args);
 6        var app = builder.Build();
 7        
 8        app.UseDefaultFiles();
 9        
10        app.UseStaticFiles();
11        
12        app.Run(async (context) =>
13        {
14            await context.Response.WriteAsync("Request Handled and Response Generated");
15        });
16        
17        app.Run();
18    }
19}
Important

Please ensure to set up multiple projects at startup.

Also, make sure to authorize CORS by amending the host.json file.

 1{
 2  "IsEncrypted": false,
 3  "Values": {
 4    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
 5    "FUNCTIONS_WORKER_RUNTIME": "dotnet"
 6  },
 7  "Host": {
 8    "CORS": "*"
 9  }
10}
Information

Our foundational code is rather straightforward, primarily comprising a request to retrieve either a list of customers or a specific customer. While seemingly unremarkable, this basic setup serves as a suitable starting point to demonstrate more advanced concepts in action.

Now, let's delve into the crux of the matter. We'll commence by exploring how to execute queries against a GraphQL server.

Advanced GraphQL concepts with HotChocolate - Part 3