Tuesday 18 February 2020

DotnetCore GraphQL implementation in WebApi

GraphQL is a Modern API architecture that use some standard query to make HTTP request.
You can explore more about GrapQL on official website. In this post we will described how we can create GraplQL API in existing .net core API. So that we will have both Rest and GraphQL within same App.

In GraphQL, API consist implementation of

  • Schema : Contains definition of
    • Query : That is used to fetch data.
    • Mutation : That is used to manipulate data
  • Types : Define data model like DTO.

To implement all these we would require following packages, which you can download from Nuget:

    <PackageReference Include="GraphQL" Version="3.0.0-preview-1352" />
    <PackageReference Include="GraphQL.Server" Version="" />
    <PackageReference Include="GraphQL.Server.Core" Version="3.5.0-alpha0027" />
    <PackageReference Include="GraphQL.Server.Transports.AspNetCore" Version="3.5.0-alpha0027" />
    <PackageReference Include="GraphQL.Server.Ui.Playground" Version="3.5.0-alpha0027" />
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />

Notice we have added GraphQL.Server.Ui.Playground, which we will be using for documentation like swagger and others. There we can explore all queries, mutations and types. As well as we can play with these in editor.

So let's start exploring  a solution from GitHub  in which we have projects:
1. DotNetCoreGraphQl.Order.WebApi
2. DotNetCoreGraphQl.Order.ViewModels
3. DotNetCoreGraphQl.Order.Providers
4. DotNetCoreGraphQl.Order.Ql

After having implementation we can make query and mutation call to endpoint /graphql in exposed UI http://localhost:60132/ui/playground

  "query" {
    "orderDetails(orderId": "12)",
      "product" {

mutation {
  addToCart(cart: {
    "quantity": 1,
    "productId": 212,
    "remarks": "Its too good"
  }) {

Key Points:
1. Each ObjectGraphType must be register.
2. Use EnableMetrics = true/false to get extensions node in response.
3. Use app.UseGraphQL() to change default endpoint (/graphql)
4. Use app.UseGraphQLPlayground() to change UI playground url (/ui/playground)

Demo on GitHub