GraphQL Library C# (.NET) — GraphQL.NET
GraphQL is a query language for APIs that allows clients to request only the data they actually need. In the .NET ecosystem, one of the most popular implementations is the GraphQL.NET library (also known as graphql-dotnet). It provides powerful tools for creating flexible, typed, and efficient APIs on the C# (.NET) platform.
In this article, we will take a detailed look at how to use GraphQL.NET, break down key concepts, and provide practical code examples.
What is GraphQL.NET?
GraphQL.NET is an open-source library that implements the GraphQL specification for the .NET platform. It supports both .NET Core and .NET Framework. Key features include:
- Creating strongly typed schemas in C#.
- Support for Queries, Mutations, and Subscriptions.
- Built-in validation and query execution.
- Integration with popular web frameworks (ASP.NET Core, Nancy, and others).
- Support for subscriptions via WebSockets (SignalR).
Installation and Setup
To get started, install the package via NuGet:
dotnet add package GraphQLdotnet add package GraphQL.SystemTextJson // for JSON serializationIf you are using ASP.NET Core, additionally install:
dotnet add package GraphQL.Server.Transports.AspNetCoredotnet add package GraphQL.Server.Ui.Playground // built-in UI for testingCreating Your First Schema
GraphQL is built around a schema that defines data types and available operations. Let's look at a simple example — an API for retrieving book information.
Step 1. Define the data model:
public class Book{ public string Id { get; set; } public string Title { get; set; } public string Author { get; set; } public int Pages { get; set; }}Step 2. Create GraphQL types:
public class BookType : ObjectGraphType<Book>{ public BookType() { Field(x => x.Id).Description("Book ID"); Field(x => x.Title).Description("Book title"); Field(x => x.Author).Description("Author"); Field(x => x.Pages).Description("Number of pages"); }}Step 3. Define the root Query:
public class BookQuery : ObjectGraphType{ public BookQuery(IDataStore dataStore) { Field<BookType>("book") .Arguments(new QueryArguments(new QueryArgument<StringGraphType> { Name = "id" })) .Resolve(context => dataStore.GetBookById(context.GetArgument<string>("id")));
Field<ListGraphType<BookType>>("books") .Resolve(context => dataStore.GetAllBooks()); }}Step 4. Assemble the schema:
public class BookSchema : Schema{ public BookSchema(IServiceProvider provider) : base(provider) { Query = provider.GetRequiredService<BookQuery>(); }}Integration with ASP.NET Core
Register services in Program.cs (or Startup.cs):
builder.Services.AddGraphQL(b => b .AddSystemTextJson() .AddSchema<BookSchema>() .AddGraphTypes(typeof(BookType).Assembly));
builder.Services.AddScoped<IDataStore, InMemoryDataStore>();Add middleware:
app.UseGraphQL<BookSchema>(); // default endpoint /graphqlapp.UseGraphQLPlayground(); // UI for testing (optional)Executing a Query
Now you can