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");
});
// ...
}
}
Join the conversation! Your thoughts help the community grow.