Setting Up GraphQL API with .NET Core Locally

Set Up GraphQL API in .NET Core | Beginner-Friendly Guide

GraphQL has emerged as a powerful alternative to REST, providing flexibility and efficiency for API development. It enables clients to request only the data they need, reducing over-fetching and under-fetching issues. In this guide, we will set up a GraphQL API using GraphQL.NET in a .NET Core application, define queries, mutations, and resolvers, and test the API using GraphQL Playground.

By the end of this tutorial, you will have a fully functional local GraphQL API, ready for development and debugging.


1. Install GraphQL.NET and Configure a GraphQL API

1.1 Prerequisites

Before setting up GraphQL in .NET Core, ensure you have the following installed:

  • .NET Core SDK (8.0 or latest version)
  • Visual Studio or VS Code
  • Postman or GraphQL Playground

1.2 Create a .NET Core API Project

First, create a new ASP.NET Core Web API:

dotnet new webapi -o GraphQLDemo
cd GraphQLDemo

1.3 Install GraphQL.NET Packages

GraphQL.NET provides the necessary libraries to build a GraphQL API in .NET Core. Install the required NuGet packages:

dotnet add package GraphQL.Server.Transports.AspNetCore
dotnet add package GraphQL.SystemTextJson
dotnet add package GraphQL.Server.Ui.Playground

1.4 Configure GraphQL in Startup

Modify Program.cs to add GraphQL support:

using GraphQL;
using GraphQL.Server;
using GraphQL.Types;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();

// Add GraphQL services
builder.Services.AddGraphQL(options =>
{
    options.EnableMetrics = false;
})
.AddSystemTextJson()
.AddGraphTypes(ServiceLifetime.Scoped);

var app = builder.Build();

app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.MapGraphQL();
});

app.Run();

This sets up a basic GraphQL server in a .NET Core Web API project.


2. Define Queries, Mutations, and Resolvers

2.1 Creating a Data Model

Define a simple Book model:

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

2.2 Create a Query Type

Define a BookQuery class to handle GraphQL queries:

public class BookQuery : ObjectGraphType
{
    public BookQuery()
    {
        Field<ListGraphType<BookType>>(
            "books",
            resolve: context => new List<Book>
            {
                new Book { Id = 1, Title = "GraphQL for .NET", Author = "John Doe" },
                new Book { Id = 2, Title = "Mastering GraphQL", Author = "Jane Smith" }
            }
        );
    }
}

2.3 Define a Mutation Type

Create a BookMutation class for adding books:

public class BookMutation : ObjectGraphType
{
    private static List<Book> books = new();

    public BookMutation()
    {
        Field<BookType>(
            "addBook",
            arguments: new QueryArguments(
                new QueryArgument<NonNullGraphType<StringGraphType>> { Name = "title" },
                new QueryArgument<NonNullGraphType<StringGraphType>> { Name = "author" }
            ),
            resolve: context =>
            {
                var book = new Book
                {
                    Id = books.Count + 1,
                    Title = context.GetArgument<string>("title"),
                    Author = context.GetArgument<string>("author")
                };
                books.Add(book);
                return book;
            }
        );
    }
}

2.4 Register GraphQL Schema

Create a BookSchema class:

public class BookSchema : Schema
{
    public BookSchema(IServiceProvider provider) : base(provider)
    {
        Query = provider.GetRequiredService<BookQuery>();
        Mutation = provider.GetRequiredService<BookMutation>();
    }
}

Register schema in Program.cs:

builder.Services.AddScoped<BookQuery>();
builder.Services.AddScoped<BookMutation>();
builder.Services.AddScoped<ISchema, BookSchema>();

3. Use GraphQL Playground for Testing Locally

3.1 Enable GraphQL Playground

Modify Program.cs to use GraphQL Playground:

app.UseGraphQLPlayground(new GraphQL.Server.Ui.Playground.GraphQLPlaygroundOptions
{
    Path = "/ui/playground"
});

3.2 Running the GraphQL API

Run the application:

dotnet run

Open http://localhost:5000/ui/playground in a browser and execute the following queries:

Query to Fetch Books

query {
  books {
    id
    title
    author
  }
}

Mutation to Add a New Book

mutation {
  addBook(title: "GraphQL in Action", author: "Alex Johnson") {
    id
    title
    author
  }
}

Conclusion

We have successfully set up a GraphQL API with .NET Core, including:

  • Installing GraphQL.NET and configuring a GraphQL API
  • Defining queries, mutations, and resolvers
  • Using GraphQL Playground for local testing

By following these steps, you can now develop and test GraphQL APIs locally, ensuring efficient data retrieval and flexibility in your applications.

Sandip Mhaske

I’m a software developer exploring the depths of .NET, AWS, Angular, React, and digital entrepreneurship. Here, I decode complex problems, share insightful solutions, and navigate the evolving landscape of tech and finance.

Post a Comment

Previous Post Next Post