Skip to main content

Building Your First App

This document will help walk you through creating a new Web API project, installing the GraphQL ASP.NET library and writing your first controller.

Create a New Web API Project

💻 Setup a new ASP.NET Core Web API project:

web api project

Add the Package From Nuget

💻 Add the GraphQL.AspNet nuget package:

# Using the dotnet CLI
> dotnet add package GraphQL.AspNet

Create a Controller

💻 Create your first Graph Controller:

BakeryController.cs
using GraphQL.AspNet.Attributes;
using GraphQL.AspNet.Controllers;

public class BakeryController : GraphController
{
[QueryRoot("donut")]
public Donut RetrieveDonut()
{
return new Donut()
{
Id = 3,
Name = "Snowy Dream",
Flavor = "Vanilla"
};
}
}

public class Donut
{
public int Id { get; set; }
public string Name { get; set; }
public string Flavor { get; set; }
}

Configure Startup

💻 Register GraphQL with your services collection and your application pipeline:

Program.cs
using GraphQL.AspNet.Configuration;

var builder = WebApplication.CreateBuilder(args);

// Add graphql services to the DI container.
builder.Services.AddGraphQL();

var app = builder.Build();

// Configure the HTTP request pipeline.
app.UseGraphQL();
app.Run();

The configuration steps may vary slightly when using a Startup.cs file; typical for .NET 5 or earlier

Execute a Query

💻 Start the application and using your favorite tool, execute a query:

Sample Query
query {
donut {
id
name
flavor
}
}

Results:

query results

The port number on your app may be different than that shown in the image