GraphQL is rapidly becoming the go-to approach for flexible, efficient APIs — letting clients specify exactly what data they need and minimizing over-fetching. If you’re building APIs with .NET Core, HotChocolate is one of the best libraries to bring GraphQL into your project easily and powerfully.
In this post, we’ll walk through setting up HotChocolate in a .NET Core Web API project and building a simple GraphQL endpoint.
Why GraphQL?
Traditional REST APIs often require multiple endpoints and over-fetch data you don’t need. GraphQL solves this by letting clients send queries that specify exactly the data shape they want — making your API more efficient and flexible.
Setting Up HotChocolate
Step 1: Create a new ASP.NET Core Web API Project
dotnet new webapi -n GraphQLDemo
cd GraphQLDemo
Step 2: Add HotChocolate Packages
dotnet add package HotChocolate.AspNetCore
dotnet add package HotChocolate.Data.EntityFramework
Defining Your Schema and Types
Create a simple model, for example, a Book
entity:
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
}
Create a query type to expose books:
public class Query
{
public IEnumerable<Book> GetBooks() =>
new List<Book>
{
new Book { Id = 1, Title = "1984", Author = "George Orwell" },
new Book { Id = 2, Title = "Brave New World", Author = "Aldous Huxley" }
};
}
Configuring HotChocolate in Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddGraphQLServer()
.AddQueryType<Query>();
var app = builder.Build();
app.MapGraphQL();
app.Run();
Testing Your GraphQL API
Run your app and navigate to https://localhost:5001/graphql
(or your port). HotChocolate provides an interactive GraphQL Playground where you can run queries like:
query {
books {
id
title
author
}
}
You should see the book list returned exactly as requested.
What’s Next?
- Add mutations to allow creating or updating data.
- Connect to a database with Entity Framework Core for real data.
- Add filtering, sorting, and paging capabilities with HotChocolate’s powerful features.
- Implement authorization to protect certain queries.
Summary
HotChocolate brings GraphQL into the .NET ecosystem with a modern, code-first approach that’s easy to get started with and highly extensible. For developers looking to build flexible APIs that adapt to client needs, GraphQL with HotChocolate is an excellent choice.
Feel free to comment below with your questions or topics you want me to cover next, like:
- Mutations in HotChocolate
- Integrating HotChocolate with EF Core
- Authentication and Authorization in GraphQL APIs
Happy coding!