Implement GraphQL endpoints using libraries like Hot Chocolate with ASP.NET Core

Introduction

Creating GraphQL endpoints in an ASP.NET Core web API using Hot Chocolate involves several steps. In this example, we'll create a simple GraphQL API that manages a list of books. We'll use Hot Chocolate to define the schema, query, and mutation operations. Before starting, make sure you have ASP.NET Core installed and a basic understanding of C# and web API development. You can create a new ASP.NET Core project using Visual Studio or the .NET CLI.

Step 1. Create a new ASP.NET Core Web API Project

Create a new ASP.NET Core Web API project using your preferred method.

dotnet new webapi -n GraphQLApi
cd GraphQLApi

Step 2. Install Hot Chocolate NuGet Packages

Open the GraphQLApi.csproj file and add the following Hot Chocolate packages.

<ItemGroup>
  <PackageReference Include="HotChocolate" Version="12.3.0" />
  <PackageReference Include="HotChocolate.AspNetCore" Version="12.3.0" />
</ItemGroup>

Save the changes, and restore the packages:

dotnet restore

Step 3. Define the GraphQL Schema

Create a class for your GraphQL schema. In this example, we'll define a simple schema for managing books.

using HotChocolate.Types;

Author: Sardar Mudassar Ali Khan
public class Book
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
}

public class Query
{
    [UsePaging]
    [UseFiltering]
    [UseSorting]
    public IQueryable<Book> GetBooks([Service] MyDbContext context)
    {
        return context.Books;
    }
}

public class Mutation
{
    public Book AddBook([Service] MyDbContext context, Book book)
    {
        context.Books.Add(book);
        context.SaveChanges();
        return book;
    }
}

public class BookType : ObjectType<Book>
{
}

Make sure to replace MyDbContext with your actual database context class.

Step 4. Configure Hot Chocolate

In your Startup.cs file, add the following code to configure Hot Chocolate.

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

Author: Sardar Mudassar Ali Khan
public class Startup
{
    // ...

    public void ConfigureServices(IServiceCollection services)
    {
        // Add GraphQL services
        services.AddGraphQL(sp => SchemaBuilder.New()
            .AddQueryType<Query>()
            .AddMutationType<Mutation>()
            .AddType<BookType>()
            .AddServices(sp)
            .Create());

        // Add database context
        services.AddDbContext<MyDbContext>(options =>
        {
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
        });

        // ...
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // ...

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapGraphQL("/graphql");
        });

        // ...
    }
}

Step 5. Create a Database Context

Create a database context class that inherits from DbContext and represents your database schema.

Author: Sardar Mudassar Ali Khan
{
  "ConnectionStrings": {
    "DefaultConnection": "your_connection_string_here"
  },
  // ...
}

Step 6. Create a Controller

Create a controller for handling GraphQL requests. Create a file named GraphQLController.cs with the following content.

using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

Author: Sardar Mudassar Ali Khan
[Route("graphql")]
[ApiController]
public class GraphQLController : ControllerBase
{
    private readonly IRequestExecutor _executor;

    public GraphQLController(IRequestExecutor executor)
    {
        _executor = executor;
    }

    [HttpPost]
    public async Task<IActionResult> PostAsync([FromBody] GraphQLRequest request)
    {
        var result = await _executor.ExecuteAsync(request);
        return Ok(result);
    }
}

Step 7. Run the Application

You can now run your ASP.NET Core web API project.

dotnet run

Your GraphQL API should be accessible at http://localhost: 'YourPortNumber'/graphql. You can use a tool like Postman or GraphQL Playground to send queries and mutations.

That's it! You've created a GraphQL API using Hot Chocolate with ASP.NET Core. You can extend this example to add more types, queries, and mutations to meet your application's requirements.

Conclusion

In this guide, we walked through the steps to create a GraphQL API using Hot Chocolate with ASP.NET Core. Here's a recap of what we covered:

  1. Create a New ASP.NET Core Web API Project: We started by creating a new ASP.NET Core Web API project using the .NET CLI or Visual Studio.
  2. Install Hot Chocolate NuGet Packages: We added the Hot Chocolate NuGet packages to the project to enable GraphQL support.
  3. Define the GraphQL Schema: We defined a simple GraphQL schema for managing books, including query and mutation operations, and created the necessary classes and types.
  4. Configure Hot Chocolate: In the Startup.cs file, we configured Hot Chocolate to use our schema, added the database context, and configured the database connection string.
  5. Create a Database Context: We created a database context class that inherits from DbContext to interact with the database.
  6. Configure Connection String: We configured the database connection string in the appsettings.json file.
  7. Create a Controller: We created a controller to handle GraphQL requests, which takes the request, executes it using Hot Chocolate, and returns the result.
  8. Run the Application: Finally, we ran the ASP.NET Core web API project, making the GraphQL API accessible at http://localhost: 'YourPortNumber'/graphql.

You can extend this example by adding more types, queries, and mutations to suit your application's needs. Hot Chocolate offers extensive capabilities for building complex and efficient GraphQL APIs in ASP.NET Core. Feel free to explore the Hot Chocolate documentation for more advanced features and customization options.


Similar Articles