GraphQL.NET in ASP.NET Core 3.1
Problem
Solution
You can easily design and build the GraphQL.NET powered API using ASP.NET Core 3.1 using the steps as shown below. Additionally, you can use the GraphQL.NET Playground to test the API from your dev environment.
1. Create a new Empty ASP.NET Core 3.1 application in Visual Studio 2019.
2. With the ASP.NET Core application open in Visual Studio, enter the below commands one by one to install the packages.
Install-Package GraphQL -Version 3.0.0-preview-1490 Install-Package GraphQL.Server.Ui.Playground -Version 3.5.0-alpha0046 Install-Package GraphQL.Server.Core -Version 3.5.0-alpha0046 Install-Package GraphQL.Server.Transports.AspNetCore -Version 3.5.0-alpha0046 Install-Package GraphQL.Server.Transports.AspNetCore.NewtonsoftJson -Version 3.5.0-alpha0046
3. Once these packages are installed, let’s start adding the model, repository and the GraphQL types. Let’s create a class Post and define the properties – Title, Author and CreatedDate.
using System; public class Post { public string Title { get; set; } public string Author { get; set; } public DateTime CreatedDate { get; set; } }
4. The Next Step is to create the Posts Repository with the GetAll() method that returns all the blog posts. Ensure that you add the following namespaces
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; public class PostRepository { public Task<List<Post>> GetAll() { List<Post> posts = new List<Post>(); posts.Add(new Post { Author = "Senthil", CreatedDate = new DateTime(2019, 11, 01), Title = "Post 1" }); posts.Add(new Post { Author = "Ashwini", CreatedDate = new DateTime(2020, 11, 01), Title = "Post 2" }); posts.Add(new Post { Author = "Norton", CreatedDate = new DateTime(2020, 01, 01), Title = "Post 3" }); posts.Add(new Post { Author = "Santhosh", CreatedDate = new DateTime(2020, 02, 01), Title = "Post 4" }); posts.Add(new Post { Author = "Lohith", CreatedDate = new DateTime(2020, 03, 01), Title = "Post 5" }); posts.Add(new Post { Author = "Senthil", CreatedDate = new DateTime(2020, 04, 01), Title = "Post 6" }); return Task.FromResult(posts.ToList()); } }
5. Now, it’s time to create the GraphQL schema with the GraphQL Type and the Query. To create the Posts Type, inherit the class from the ObjectGraphType<Post> and define the fields that this type can accept. In our case, the user can provide any or all of the fields defined (Title, Author, CreatedDate)
public class PostType : ObjectGraphType<Post> { public PostType() { Field(t => t.Title); Field(t => t.Author); Field(t => t.CreatedDate); } }
The Query class (PostQuery) needs to be inherited from the ObjectGraphType and in the constructor we define the name of the query as “posts” which is the name the client or end user will be using. While defining the query, we also have defined the resolve method from where the data needs to be retrieved. In our case, it’s the product repository’s GetAll method.
public class PostQuery : ObjectGraphType { private PostRepository _productRepository; public PostQuery(PostRepository productRepository) { _productRepository = productRepository; Field<ListGraphType<PostType>>( "posts", resolve: context => productRepository.GetAll() ); } }
Finally, we need to define the schema and specify the query for it as shown below.
public class BlogPostSchema : Schema { public BlogPostSchema(IServiceProvider provider) : base(provider) { Query = provider.GetRequiredService<PostQuery>(); } }
Don’t forget to include the below necessary namespaces for the GraphQL.NET
public class BlogPostSchema : Schema { public BlogPostSchema(IServiceProvider provider) : base(provider) { Query = provider.GetRequiredService<PostQuery>(); } }
Don’t forget to include the below necessary namespaces for the GraphQL.NET
using GraphQL.Types; using GraphQL.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks;
6. it’s time to setup our ASP.NET Core Services to understand GraphQL types that we created.
Add the below code to the ConfigureServices in the Startup.cs.
public void ConfigureServices(IServiceCollection services) { services.AddScoped<PostRepository>(); services.AddScoped<PostQuery>(); services.AddScoped<PostType>(); services.AddScoped<BlogPostSchema>(); services.Configure<IISServerOptions>(options => { options.AllowSynchronousIO = true; }); services.AddGraphQL(o => { o.ExposeExceptions = true; }) .AddGraphTypes(ServiceLifetime.Scoped).AddNewtonsoftJson(); }
Add the below code to the Configure method in the Startup.cs.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseGraphQL<BlogPostSchema>("/graphql"); app.UseGraphQLPlayground(new GraphQLPlaygroundOptions()); }
7. Finally, run the application on IISExpress and visit the URL <localhost :< port>>/ui/playground. You should see the GraphQL Playground. In the Left side of the GraphQL Playground, enter the query name that you wish to use (in our example, we will be using “posts”) and then specify which field (Title in our example) that you need the data to be retrieved from the API.