In this article, we are going to learn how to set up GraphQL in ASP.NET Core application. We are going to use different third-party libraries to make this integration easier and will explain in detail how to use GraphQL elements (Type, Query, and Schema) to complete the integration process of GraphQL in ASP.NET Core.

To download the source code, visit the GraphQL in ASP.NET Core Project Source Code.

For the complete navigation of this tutorial visit GraphQL ASP.NET Core Tutorial.

We’ve divided this article into the following sections:

About GraphQL and How it’s Different from REST

GraphQl is a query language. It executes queries by using type systems which we define for our data. GraphQL isn’t tied to any specific language or a database, just the opposite, it is adaptable to our code and our data as well.

Let’s talk a bit about how GraphQL differs from REST:

  • GraphQL requires fewer roundtrips to the server and back to fetch all the required data for our view or template page. With REST, we have to visit several endpoints (api/subjects, api/professors, api/students …) to get all the data we need for our page, but that’s not the case with GraphQL. With GraphQL, we create only one query which calls several resolvers (functions) on the server side and returns all the data from different resources in a single request.
  • With REST, as our application grows, the number of endpoints grows as well, and that requires more and more time to maintain. But, with GraphQL we have only one endpoint api/graphql and that is all.
  • By using GraphQL, we never face a problem of getting too much or too few data in our response. That’s because we are defining our queries with the fields which states what we need in return. That way, we are always getting what we have requested. So, if we send a query like this one:

We are 100% sure that we will get this response back:

With REST this is not the case. Sometimes we get more than we need and sometimes less, it depends on how actions on a certain endpoint are implemented.

These are the most important differences between REST and GraphQL. Now that we know that, let’s create a basic project to demonstrate how to set up GraphQL.

Introduction to a Starter ASP.NET Core Web API Project

We have prepared a starter ASP.NET Core project, which you can download here GraphQL ASP.NET Core Starter Project. We strongly recommend you download this project, but if you want, you can create your own as well. The starter project has the following structure:

Starter project structure - GraphQL in ASP.NET Core

The Contracts folder contains interfaces required for our repository logic:

In the Entities folder, we keep model classes with a context class and the seed configuration classes:

And in a Repository folder, we have classes related to the data fetching logic:

This repository logic has the basic setup without any additional layers. But if you want to learn more about Repository Pattern in ASP.NET Core, we have a great article for you to read ASP.NET Core Web API – Repository Pattern.

The context class and repository classes are registered inside the Startup.cs class:

So, at this point, all you have to do is to modify connection string (if you have to) in the appsettings.json file and to navigate to the Package Manager Console and run the update-database command. Once you do that, we are ready to move on.

As you can see, we are using the Code-First approach in the starter project.

Integration of GraphQL in ASP.NET Core

Since the GraphQL support is not provided inside the ASP.NET Core applications, we have to install a few new libraries. So,  the first library we are going to install is GraphQL and we can install it via NuGet package manager:

GraphQL package - GraphQL in ASP.NET Core

In addition, we can use the Package Manager Console: PM> Install-Package GraphQL -Version 2.4.0

The second library we want to install is GraphQL.Server.Transports.AspNetCore, which will help us to get GraphQL.NET as a dependency:

Second NuGet package - GraphQL in ASP.NET Core

The Package Manager command: PM> Install-Package GraphQL.Server.Transports.AspNetCore -Version 3.4.0

Finally, we are going to install GraphQL.Server.Ui.Playground library, which will help us send the GraphQL queries to the server:

Ui Playground package - GraphQL in ASP.NET Core

The PM command: PM> Install-Package GraphQL.Server.Ui.Playground -Version 3.4.0

Once we are finished with the installations, we can move on to the integration logic.

Creating GraphQL Specific Objects (Type, Query, Schema)

Let’s start by creating a new folder named GraphQL and inside a new one with the name GraphQLSchema with a single class AppSchema.cs:

GraphQL structure - GraphQL in ASP.NET Core

This class must inherit from the Schema class which resides in the GraphQL.Types namespace. Inside the constructor, we inject the IdependencyResolver which is going to help us resolve our Query, Mutation or Subscription objects.

What’s important to know is that each of the schema properties (Query, Mutation or Subscription) implements IObjectGraphType which means that the objects we are going to resolve must implement the same type as well. This also means that our GraphQL API can’t return our models directly as a result but GraphQL types which implement IObjectGraphType instead.

So, let’s leave this class for a moment and create a new folder GraphQLTypes with a single class OwnerType.cs inside the GraphQL folder:

This is the OwnerType class which we use as a replacement for the Owner model inside a GraphQL API. This class inherits from a generic ObjectGraphType<Owner> class which at some point (in the hierarchy) implements IObjectGraphType interface. With the Field method, we specify the fields which represent our properties from the Owner model class.

To continue on, let’s create another folder GraphQLQueries with a class AppQuery, inside the GraphQL folder.

But before we modify this class, let’s modify the IOwnerRepository interface:

And the OwnerRepository class:

Now, we can modify the AppQuery class to reflect those changes:

AppQuery Explanation

As we can see, this class inherits from the ObjectGraphType as well, just the non-generic one. Moreover, we inject our repository object inside a constructor and create a field to return the result for the specific query.

In this class, we use the generic version of the Field method which accepts some „strange“ type as a generic parameter. Well, this is the GraphQL.NET representation for the normal .NET types. So, ListGraphType is the representation of the List type, and of course, we have IntGraphType or StringGraphType, etc… For the complete list visit SchemaTypes in GraphQL .NET.

The „owners“ parameter is a field name (query from the client must match this name) and the second parameter is the result itself.

Having  done our preparations, we can now modify our AppSchema class:

Well done. Let’s proceed to schema registration.

Libraries and Schema Registration

In a Startup class, we need to register our installed libraries and the created schema class as well. So, let’s do that by modifying the ConfigureServices and Configure methods:

In the ConfigureServices method, we register the DependencyResolver (for our queries) and the schema class as well. Furthermore, we register GraphQL with the AddGraphQL method and register all the GraphQL types (Query and Type classes) with the AddGraphTypes method. Without this method, we would have to register all the types and queries manually in our API.

Finally, in the Configure method, we are adding our schema to the request’s pipeline as well as the Playground UI tool which we are just about to use.

Sending the First Query

To test our GraphQL API, we are going to use the GraphQL.UI.Playground tool. So, let’s first start our server application and then navigate to the https://localhost:5001/ui/playground address:

Sending the first query

Excellent, we see that everything is working just as it supposed to. As soon as we send our query, with the name „owners“ (which must match the query name we created in the AppQuery file), we get the required result.

Conclusion

Our integration is complete. We have seen how in few easy steps we can integrate GrapnQL in ASP.NET Core and how to retrieve required results with the query.

In the next article, we are going to learn about advanced GraphQL Queries, how to handle errors during queries and how to use data loader to cache our results.

If you have enjoyed reading this article and if you would like to receive the notifications about the freshly published .NET Core content we encourage you to subscribe to our blog.