GraphQL API with C#: Step-by-Step Tutorial for Beginners

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 with C#



GraphQL is a query language for APIs developed by Facebook that allows clients to request only the data they need. Unlike REST, where endpoints are fixed, GraphQL enables flexible server responses. In this tutorial, we will build a full-fledged GraphQL API in C# using the Hot Chocolate library — the most popular solution for .NET.



We will go from installation to implementing queries, mutations, and subscriptions. By the end of this article, you will be able to independently deploy a GraphQL server in C# and integrate it into your projects.



1. Project Setup and Configuration



First, let's create a new ASP.NET Core project. Make sure you have the .NET SDK (version 6.0 or higher) installed. Open a terminal or command prompt and run:



dotnet new web -n GraphQLDemocd GraphQLDemo


Now install the Hot Chocolate package:



dotnet add package HotChocolate.AspNetCoredotnet add package HotChocolate.AspNetCore.Playground


After installation, open the Program.cs file and configure the server:



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();

// Add Playground for testingapp.UsePlayground();

app.Run();


Now create a simple Query class in a separate file Query.cs:



public class Query{    public string Hello() => "Hello, GraphQL world!";}


Run the project with the command dotnet run and open your browser at http://localhost:5000/graphql. You will see the Playground interface where you can execute a query:



{  hello}


Response: { "data": { "hello": "Hello, GraphQL world!" } }



2. Creating Types and Queries



GraphQL is strongly typed. In C#, we use classes to define types. Let's create a Book and Author model:



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

public class Author{ public int Id { get; set; } public string Name { get; set; } public List<Book> Books { get; set; }}


Now add a data store (in a real project, use a database) and extend the Query class:



public class Query{    private static List<Author> _authors = new()    {        new Author        {            Id = 1,            Name = "Leo Tolstoy",            Books = new List<Book>            {                new Book { Id = 1, Title = "War and Peace", Author = null },                new Book { Id = 2, Title = "Anna Karenina", Author = null }            }        },        new Author        {            Id = 2,            Name = "Fyodor Dostoevsky",            Books = new List<Book>            {                new Book { Id = 3, Title = "Crime and Punishment", Author = null }            }        }    };

public List<Author> GetAuthors() => _authors;

public Author GetAuthor(int id) => _authors.FirstOrDefault(a => a.Id == id); public List<Book> GetBooks() => _authors.SelectMany(a => a.Books).ToList();}


Note: we didn't explicitly configure types — Hot Chocolate automatically generates the schema based on C# classes. Now you can execute queries:



{  authors {    id    name    books {      title    }  }}

Blogs

Book Recommendations