GraphQL in .NET: Practical usage

Introduction

In our first article, we learned why there is a need for GraphQL and what are the differences between GraphQL and REST. Starting from this article, we will dive into details of the practical usage of GraphQL.

GraphQL in practice

There are many libraries for working with GraphQL on the .NET platform, and one of them is called Hot Chocolate.

By being a graphQL library and server, Hot Chocolate insulates us from the details and complexities of graphQL.

PS: Please use the graphQL repo for examples.

Let's take the following steps to put GraphQL into practice: (001_GraphQLEssentials project from the repo)

  1. Select the asp.net core empty project from Visual Studio. (If you are not using Visual Studio, create the project by writing "dotnet new web" in any folder)
  2. install the hotchocolate library by typing install-package hotchocolate. aspnetcore
  3. Go to the Program.cs file and make the following change.
using _001_GraphQLEssentials.Queries;

namespace _001_GraphQLEssentials
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);
            builder.Services.AddGraphQLServer()
                .AddQueryType<Query>();

            var app = builder.Build();

            app.MapGraphQL();

            app.Run();
        }
    }
}

AddGraphQLServer() allows us to add the Hotchocoloate graphQL server to work with graphQL. Also, with the AddQueryType() method, we select the type over which graphQL will perform data exchange. Finally, we configure routing with MapGraphQL(). By default, /graphql routing is set.

4) Let's add our models that will participate in data exchange.

public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public List<Card> Cards { get; set; }
    }

 public class Card
    {
        public int Id { get; set; }
        public string Number { get; set; }
        public string CVC { get; set; }
        public string ExpiryDate { get; set; }
    }

5) Let's implement the data layer using the GetCustomers method.

namespace _001_GraphQLEssentials.Queries
{
    public class Query
    {
        public IEnumerable<Customer> GetCustomers()
        {
            return new
                Customer[]
            {
                new Customer{ Id = 1, Email = "[email protected]", Name = "Baki",
                Cards = new List<Card>()
                {
                    new Card{ Number = "1234-1234-4444", CVC="653", ExpiryDate="08/28", Id = 1},
                    new Card{ Number = "7766-1234-4444", CVC="765", ExpiryDate="08/26", Id = 2},
                } },
                new Customer{ Id = 2, Email = "[email protected]", Name = "Hanamayama",
                 Cards = new List<Card>()
                {
                    new Card{ Number = "7878-3333-4444", CVC="222", ExpiryDate="08/28", Id = 3},
                    new Card{ Number = "7766-6789-1234", CVC="111", ExpiryDate="08/26", Id = 4},
                } },
                new Customer{ Id = 3, Email = "[email protected]", Name = "Doppo",
                 Cards = new List<Card>()
                {
                    new Card{ Number = "1234-1234-5456", CVC="123", ExpiryDate="08/28", Id = 5},
                    new Card{ Number = "8888-4444-4532", CVC="345", ExpiryDate="08/26", Id = 6},
                } },
                new Customer{ Id = 4, Email = "[email protected]", Name = "Dorian", Cards = new List<Card>()
                {
                    new Card{ Number = "8989-5555-4444", CVC="567", ExpiryDate="08/28", Id = 7},
                    new Card{ Number = "7766-6666-4444", CVC="789", ExpiryDate="08/26", Id = 8},
                } },
            };
        }
    }
}

After everything is ready, we can start the application and test it.

GraphQL in.NET

As we can see, by selecting "Create document" in the /graphql routing, we can see the web version of the "banana Cake Pop" application by confirming the given form.

GraphQL in.NET

We can easily see the "internal" structure of the model we will query from the "Schema reference" section. As you can see from this model, to see the "name" of the customer, you need to give a path in the form of CustomerQuery: customers: name.

GraphQL in.NET

But since we specified the CustomerQuery model in AddQueryType() in Program.cs, just routing as customers: name will suffice.

GraphQL in.NET

Query cases

If we want to get all data as customers, the following request will not work.

GraphQL in.NET

If we want to get all the data for customers.

GraphQL in.NET

As we can see, the graphQL format is kind of similar to JSON, but unlike JSON, attribute values are not given, and they are separated by just a new line.

In GraphQL, queries are divided into 2 groups.

  1. Query = HTTP GET in REST
  2. Mutation = POST, PUT, DELETE, PATCH

A typical graphQL request is an HTTP POST request.  HTTP POST is used for both: Queries and Mutations.

HTTP GET is used for Persisted Queries.

Conclusion

However, GraphQL is transport agnostic, meaning it does not depend on any specific protocol. For GraphQL, you can use HTTP, socket, grpc, etc. In the next article, we will learn more about GraphQL configuration, pagination, and sorting


Similar Articles