GraphQL API
Introduction
GraphQL is a query language for APIs and a runtime for executing those queries by using a type system you define for your data. In this tutorial, we will cover how to create and consume GraphQL APIs using .NET. We will create a GraphQL service and a client to consume this service.
Prerequisites
- Visual Studio installed with .NET development workload
- Basic knowledge of .NET and C#
Creating a GraphQL Service
First, create a new GraphQL service project in Visual Studio:
- Open Visual Studio and click "Create a new project".
- Select "ASP.NET Core Web Application" and click "Next".
- Set the name and location for your project and click "Create".
- Choose "API" as the template and click "Create".
Adding GraphQL Dependencies
Add the necessary GraphQL packages to your project via NuGet Package Manager:
- GraphQL
- GraphQL.Server.Transports.AspNetCore
- GraphQL.Server.Ui.Playground
Defining the GraphQL Schema
Define your GraphQL schema. Create a new folder named Schemas
and add the following classes:
using GraphQL.Types;
public class PersonType : ObjectGraphType<Person>
{
public PersonType()
{
Field(x => x.Id).Description("The ID of the person.");
Field(x => x.Name).Description("The name of the person.");
Field(x => x.Age).Description("The age of the person.");
}
}
using GraphQL.Types;
public class Query : ObjectGraphType
{
public Query()
{
Field<PersonType>(
"person",
arguments: new QueryArguments(
new QueryArgument<IntGraphType> { Name = "id" }
),
resolve: context => new Person
{
Id = context.GetArgument<int>("id"),
Name = "John Doe",
Age = 25
}
);
}
}
Setting Up the GraphQL Middleware
Configure the GraphQL middleware in Startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSingleton<ISchema, Schema>();
services.AddGraphQL(options =>
{
options.EnableMetrics = false;
}).AddSystemTextJson();
services.AddSingleton<PersonType>();
services.AddSingleton<Query>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseGraphQL<ISchema>();
app.UseGraphQLPlayground(new GraphQLPlaygroundOptions());
}
Running the Service
Run the service by pressing F5
or clicking the "Start" button in Visual Studio. The GraphQL Playground will be available at https://localhost:5001/ui/playground
.
Creating a GraphQL Client
Now, create a new .NET Console App to consume the GraphQL service:
- Open Visual Studio and click "Create a new project".
- Select "Console App (.NET Core)" and click "Next".
- Set the name and location for your project and click "Create".
Adding GraphQL Client Dependencies
Add the necessary GraphQL client packages to your project via NuGet Package Manager:
- GraphQL.Client
- GraphQL.Client.Serializer.SystemTextJson
Consuming the GraphQL Service
Modify the Program.cs
file to call the GraphQL service:
using System;
using System.Net.Http;
using System.Threading.Tasks;
using GraphQL;
using GraphQL.Client.Http;
using GraphQL.Client.Serializer.SystemTextJson;
namespace MyGraphQLClient
{
class Program
{
static async Task Main(string[] args)
{
using var client = new GraphQLHttpClient("https://localhost:5001/graphql", new SystemTextJsonSerializer());
var request = new GraphQLRequest
{
Query = @"
query($id: Int!) {
person(id: $id) {
id
name
age
}
}",
Variables = new { id = 1 }
};
var response = await client.SendQueryAsync<dynamic>(request);
var person = response.Data.person;
Console.WriteLine($"ID: {person.id}, Name: {person.name}, Age: {person.age}");
}
}
}
Running the Client
Run the client application by pressing F5
or clicking the "Start" button in Visual Studio. You should see the details of the person retrieved from the GraphQL service.
Conclusion
In this tutorial, we covered how to create and consume GraphQL APIs with .NET. You learned how to define a GraphQL schema, implement the service in .NET, and consume the service with a .NET client application. GraphQL provides a flexible and efficient way to work with APIs, allowing clients to request exactly the data they need. Happy coding!