October 27, 2019
In modern web development, GraphQL has become one of the most popular ways to interact with APIs. It allows clients to request exactly the data they need, providing more flexibility than traditional REST APIs. GraphQL enables clients to aggregate data from multiple sources in a single query, reducing the number of requests required.
In this post, we’ll take a look at how to integrate GraphQL into a .NET Core application, set up a basic GraphQL endpoint, and perform queries to retrieve data.
What is GraphQL?
GraphQL is a query language for your API and a runtime for executing those queries by using a type system you define for your data. Unlike REST APIs, where you often have multiple endpoints for different resources, GraphQL exposes a single endpoint that can be queried with specific fields, returning only the data you need.
Benefits of GraphQL
- Client-Specified Queries: Clients have control over the data they request, meaning they can retrieve exactly what they need and avoid over-fetching or under-fetching data.
- Single Endpoint: Instead of having many RESTful endpoints, a GraphQL API exposes a single endpoint for all interactions.
- Aggregated Data: Clients can retrieve data from multiple resources in a single request.
- Efficient Data Fetching: As clients specify their queries, GraphQL reduces unnecessary network calls and improves the performance of the application.
Setting Up GraphQL in .NET Core
To get started with GraphQL in .NET Core, we’ll use the GraphQL.Net library, which is a popular choice for implementing GraphQL APIs in .NET.
Step 1: Install GraphQL NuGet Package
First, you need to install the GraphQL.Net NuGet package. Run the following command in your terminal:
dotnet add package GraphQL
This will add the necessary package to your project, allowing you to use GraphQL within your .NET Core application.
Step 2: Define Your Data Model
For this example, let’s assume we are building a simple API to manage a list of books.
We’ll start by defining a simple data model for our book entity:
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
}
Step 3: Create a GraphQL Schema
A GraphQL schema defines the types of data that can be queried. In GraphQL.Net, we’ll define a BookType
class to specify the structure of the book data.
using GraphQL.Types;
public class BookType : ObjectGraphType<Book>
{
public BookType()
{
Field(x => x.Id);
Field(x => x.Title);
Field(x => x.Author);
}
}
Next, we define the Query class, which specifies the entry points for retrieving data. In this case, we will have a query to get a list of books.
public class Query : ObjectGraphType
{
public Query()
{
Field<ListGraphType<BookType>>(
"books",
resolve: context => GetBooks()
);
}
private List<Book> GetBooks()
{
// In a real application, you'd fetch this data from a database
return new List<Book>
{
new Book { Id = 1, Title = "The Hobbit", Author = "J.R.R. Tolkien" },
new Book { Id = 2, Title = "1984", Author = "George Orwell" }
};
}
}
In this code:
- We define a Query type that exposes a
books
field, which returns a list ofBookType
. - The
resolve
function fetches the data when the query is executed. Here, it returns hardcoded book data, but in a real-world application, you would query a database or other data source.
Step 4: Set Up the GraphQL Server
Now, let’s wire everything up in Startup.cs. We need to configure the GraphQL server and register the schema:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IDocumentExecuter, DocumentExecuter>();
services.AddSingleton<IDocumentWriter, JsonDocumentWriter>();
services.AddSingleton<Query>();
services.AddSingleton<BookType>();
services.AddSingleton<ISchema>(services => new Schema { Query = services.GetRequiredService<Query>() });
services.AddGraphQL(options =>
{
options.EnableMetrics = false;
options.ExposeExceptions = true;
}).AddSystemTextJson();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGraphQL();
});
}
In this configuration:
- We register the necessary GraphQL services, including the schema, the
Query
class, and theBookType
. - We also set up the GraphQL middleware to handle incoming queries at the
/graphql
endpoint.
Step 5: Querying the GraphQL Endpoint
Now that the server is set up, let’s query our GraphQL API. You can test your GraphQL endpoint using tools like GraphiQL, Postman, or Insomnia. To query the list of books, use the following query:
{
books {
id
title
author
}
}
This query requests the id
, title
, and author
fields of all books.
You should get a response like this:
{
"data": {
"books": [
{
"id": 1,
"title": "The Hobbit",
"author": "J.R.R. Tolkien"
},
{
"id": 2,
"title": "1984",
"author": "George Orwell"
}
]
}
}
Conclusion
In this post, we’ve introduced GraphQL and how to integrate it into your .NET Core application. GraphQL provides a more flexible and efficient way to query data compared to traditional REST APIs. We’ve covered:
- Setting up a GraphQL endpoint in .NET Core.
- Defining types and queries.
- Sending queries to fetch data.
GraphQL has many advanced features, such as mutations (for creating, updating, and deleting data), subscriptions (for real-time updates), and more. In future posts, we’ll dive deeper into these topics and explore how to make the most of GraphQL in your .NET Core applications.