GraphQL API with C#: Step-by-Step Guide for .NET Developers

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction to GraphQL and C#

GraphQL is a query language for APIs that allows clients to request only the data they actually need. Unlike REST, where the response structure is fixed, GraphQL enables flexible query formation and returns exactly what is required. In this tutorial, we will walk through creating a full-featured GraphQL API on the C# (.NET) platform using the Hot Chocolate library.

This material will be useful for both beginners and experienced developers who want to master a modern approach to building APIs. We will go through all stages: from project setup to implementing queries and mutations. By the end of the article, you will have a working GraphQL server ready for integration with any client.



Project Installation and Setup

First, we need to create a new ASP.NET Core project. Open a terminal or command line and run the command:

dotnet new web -n GraphQLDemocd GraphQLDemo

Now let's add the Hot Chocolate package — the main library for working with GraphQL in .NET:

dotnet add package HotChocolate.AspNetCore

After installation, open the Program.cs file and configure the services. Here is the minimal configuration to run GraphQL:

using Microsoft.AspNetCore.Builder;using Microsoft.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);

// Add GraphQL servicesbuilder.Services .AddGraphQLServer() .AddQueryType<Query>();

var app = builder.Build();

// Add GraphQL middlewareapp.MapGraphQL();

app.Run();

Note: we haven't created the Query class yet. This is our root type that defines available queries. We'll create it in the next section.



Schema Definition: Types and Resolvers

Creating a Data Model

Let's start by defining a simple data model. Let it be a book:

public class Book{    public string Id { get; set; }    public string Title { get; set; }    public string Author { get; set; }    public int Year { get; set; }}

Creating the Query Class

Now let's create the Query class that will return data. In Hot Chocolate, resolvers are regular methods that can be synchronous or asynchronous:

public class Query{    private static readonly List<Book> Books = new()    {        new Book { Id = "1", Title = "War and Peace", Author = "Leo Tolstoy", Year = 1869 },        new Book { Id = "2", Title = "Crime and Punishment", Author = "Fyodor Dostoevsky", Year = 1866 }    };

public IQueryable<Book> GetBooks() => Books.AsQueryable();

public Book? GetBook(string id) => Books.FirstOrDefault(b => b.Id == id);}

The GetBooks method returns a list of all books, and GetBook returns a single book by its identifier. Hot Chocolate automatically converts these methods into fields of the GraphQL schema.

Type Configuration (Optional)

Sometimes you need to explicitly specify which fields should be available. For this, you can use attributes or the Fluent API. Example with attributes:

public class Book{    [GraphQLName("id")]    public string Id { get; set; }

[GraphQLNonNullType] public string Title { get; set; }

public string Author { get; set; } public int Year { get; set; }}

Now run the project with the command dotnet run and navigate to http://localhost:5000/graphql in your browser. You will see the built-in Banana Cake Pop — an environment for testing queries.



Implementing Mutations (Create, Update, Delete)

Mutations in GraphQL are used to modify data. Let's create a Mutation class and add methods for working with books.

                

Blogs

Book Recommendations