Consuming GraphQL API In ASP.NET Core (Part 2)
Tags: graphql, dotnet, netcore
Published: 2021-01-28 10:13:05

Here's the second part of the post [HotChocolate: Introduction to GraphQL for ASP.NET Core (Part 1)](https://dev.to/jioophoenix/hotchocolate-introduction-to-graphql-for-asp-net-core-part-1-2e27). In part 1, we developed a GraphQL API using ASP.NET. In this part, we will focus on consuming the endpoint in an ASP.NET Blazor WebAssembly application. 

We will create a page that will display all the Employees along-side their Department, another page that displays a single Employee and a page with a form to create an Employee.

The code for this sample can be found on the [CloudBloq/GraphQLSampleAppUI](https://github.com/CloudBloq/GraphQLSampleAppUI) repository on GitHub. 


##Prerequisites

* [Visual Studio 2019 (version 16.8.0 upwards)](https://visualstudio.microsoft.com/vs/)


##Create the Solution and Project

After opening VS, click the Create a new project link then search for **Blazor** and select it:
![BlazorSearch](https://dev-to-uploads.s3.amazonaws.com/i/8u8ugcenb9plri45j0x2.jpg)

Give the project and solution a name **GraphQLSampleAppUI** then click **create**:
![NameProAndSolu](https://dev-to-uploads.s3.amazonaws.com/i/fvt4c08p1r5sepabsolg.jpg)
 
 Select the Blazor WebAssembly App option then click **create**:

![Template](https://dev-to-uploads.s3.amazonaws.com/i/jj5dn2bd88b141i9i1o6.jpg)
 

##Install Dependencies

We will make use of [GraphQL.Client(v 3.2.0)](https://github.com/graphql-dotnet/graphql-client) library to consume the GraphQL API. To install the package, right click the solution in the solution explorer and select **Manage NuGet Packages for Solution**. Under the Browse section, search for **GraphQL.Client** and click on it, then in the preview panel click the Install button:

![Client](https://dev-to-uploads.s3.amazonaws.com/i/uzje2peylc1lz7l73cv1.jpg)
 
Also, install the **modernhttpclient** and **GraphQL.Client.Serializer.Newtonsoft** packages respectively.


##Consume The API

In [part 1](https://dev.to/jioophoenix/hotchocolate-introduction-to-graphql-for-asp-net-core-part-1-2e27), to test the Query or Mutation, we used Banana Cake Pop:
![mutation](https://dev-to-uploads.s3.amazonaws.com/i/tufie63htcef6a1h9jm1.jpg)
![query1](https://dev-to-uploads.s3.amazonaws.com/i/uv1pckpepzr9t3b6bz7z.jpg)

In this case, we will make use of the [GraphQL.Client](https://github.com/graphql-dotnet/graphql-client) library to consume the GraphQL API. We will write all the code required to perform the Query and Mutation in a folder. Add a new folder called **DataAccess**. 

###Query

We will create a generic method that can be used to perform all the Query we need to perform. In the **DataAccess** folder, add a new C# class file called **Query.cs**:

{% gist https://gist.github.com/JIOO-phoeNIX/d27e2e1f6ea6427dfa0c40769c9cd623 %}

The way [GraphQL.Client](https://github.com/graphql-dotnet/graphql-client) works is to first create an instance of **GraphQLHttpClient** using an instance of **GraphQLHttpClientOptions** (which takes in the URI of the GraphQL Server) then use an instance of the **GraphQLRequest** to create the Query or the Mutation string that will be sent to the Server.

Line 15 defines the field graphQLHttpClient of type GraphQLHttpClient. Line 26 assigns a new instance (using an instance of GraphQLHttpClientOptions) to the graphQLHttpClient field. The other parameter is used to specify the deserializer used to deserialize the output. 

Note that if you modified line 8 in [launchSettings.json](https://github.com/CloudBloq/GraphQLSampleApp/blob/master/GraphQLSampleApp/Properties/launchSettings.json#L8) in [part 1](https://dev.to/jioophoenix/hotchocolate-introduction-to-graphql-for-asp-net-core-part-1-2e27), you also have to modify line 19 here. 

Lines 30 to 54 define the generic method **ExceuteQueryReturnListAsyn**. The generic type **T** is the type the output will be deserialized into. The parameter **graphQLQueryType** is the Query type and the parameter **completeQueryString** will contain the complete Query. From the example below, graphQLQueryType will be allDepartmentsWithEmployee and completeQueryString will be the entire string.

```graphql
query{
  allDepartmentsWithEmployee{
    name
    employees{
      email
      name
    }
  }
}
```

In line 34, an instance of **GraphQLRequest** is created which takes in the complete query string. The Query is sent to the server in line 39. The result gotten from the server will contain the Query type in the beginning so we replace it with an empty string in line 42. The output is deserialized in line 46 to the generic type. 

The **ExceuteQueryReturnListAsyn** is used when the output we are expecting is an array of the generic type. The other method **ExceuteQueryAsyn** in line 56 is the same as **ExceuteQueryReturnListAsyn** except that it should be used when we are expecting a single object of the generic type as the output. The **ExceuteQueryReturnListAsyn** and **ExceuteQueryAsyn** methods can be used to perform any Query we need and deserialize the output accordingly. 


###Mutation

In the **DataAccess** folder, add a new C# class file called **Mutation.cs**:

{% gist https://gist.github.com/JIOO-phoeNIX/6adf5bb5222147c0415ab3845aa73373 %}

This code in this class follows the same pattern as the **Query.cs**. Line 27 defines the generic method **ExceuteMutationAsyn**, it takes in the same parameter as the **ExceuteQueryAsyn**, sends the Mutation to the server and deserializes the output to the generic type T.


##The Models

We will need the models that the Query and Mutation output will be deserialized into. Add a new folder **Model** in the **DataAccess** folder. Add a new C# class **Employee.cs** to the **Model** folder:

{% gist https://gist.github.com/JIOO-phoeNIX/4350e7efcaeb6ea911c68b3744d1c8f5 %}

Add another C# class file **Department.cs** to the **Model** folder:

{% gist https://gist.github.com/JIOO-phoeNIX/ec04dbc1fe000168c8cf66b8e5150fc2 %}

We need another model that will be used for the form used to create an Employee. Add another C# class file **CreateEmployeeModel.cs** to the **Model** folder:

{% gist https://gist.github.com/JIOO-phoeNIX/87b834ba72d191f4f50bb87360ecd69d %}
The validations added to the properties (Required, EmailAddress...) via attributes will be used by the form to validate the input.

We need another model that will be used to hold the output of response when we create an Employee. Add another C# class file **CreateEmployeeReturnModel.cs** to the **Model** folder:

{% gist https://gist.github.com/JIOO-phoeNIX/2513ca7308143e5fbeb1a5a111356b85 %}


##Blazor Pages

First, we will create the page that will be used to display all the Employees. In the **Pages** folder, add a new Razor Component called **EmployeeView.razor**:

{% gist https://gist.github.com/JIOO-phoeNIX/33741d1f27f5ec0c93943dbb3193dc76 %}

The variable AllEmployees on line 43 is used to store the Employees. You see how I called the **ExceuteQueryReturnListAsyn** passing in the type **Employee** and the parameters. The variable AllEmployees is checked first if it contains any item on line 13, if it does then the data is displayed in the table in lines 19 to 39. 

Next, we will create the page that will be used to display the individual Employee detail. In the **Pages** folder, add a new Razor Component called **ViewEmployee.razor**:

{% gist https://gist.github.com/JIOO-phoeNIX/be8eae6acc50b757afb92fb964f95f9d %}

The **ExceuteQueryAsyn** method is used to get the Employee details in line 54. The Id is gotten from the URI and is attached to the string sent to the server in line 51. 

Next, we will create the page that will be used to create an Employee. In the **Pages** folder, add a new Razor Component called **CreateEmployee.razor**:

{% gist https://gist.github.com/JIOO-phoeNIX/fe3d90fdb876be1838b95f5a5a5af9ef %}

Lines 12 to 33 define the form used to receive the data. The form uses the model **CreateEmployeeModel** via the variable createEmployee. The method **ExceuteMutationAsyn** is called on line 56, and the type **CreateEmployeeReturnModel** is passed as the return type. Notice how the form data is bound to the string on line 53.

Finally, we need to modify the **NavMenu.razor** in the **Shared** folder:

{% gist https://gist.github.com/JIOO-phoeNIX/c16da7481b3e69de6423d3b5a60fe7fa %}


##Running the Application

Ensure the GraphQL server [https://localhost:44351/graphql/](https://localhost:44351/graphql/) is running first. Right-click the solution and click Build Solution. After Build is successful, click CTRL + f5 or f5 to run the application. You should get:

![run1](https://dev-to-uploads.s3.amazonaws.com/i/0fff10kjzr87xewaix0w.jpg)
 
If you click the **Employee** link, you should get:

![run2](https://dev-to-uploads.s3.amazonaws.com/i/hpyovklf8b4ca6leurve.jpg)

Click the **Create an Employee** link and try to click the Create button without entering any data in the form, you should get the response:

![run3](https://dev-to-uploads.s3.amazonaws.com/i/kzrb5yp5oc0nos6hairv.jpg)

 If you enter an invalid email or an age that isn't between 20 and 50, you should get the validation failed error.


This isn't the end of learning Blazor and GraphQL. There are a lot of things to explore, especially in Blazor WebAssembly. The links below will help you if you are really interested in learning more:
* [Blazor: Getting Started](https://app.pluralsight.com/library/courses/getting-started-blazor/table-of-contents?aid=7010a000002LUv2AAG)
* [Building GraphQL APIs with ASP.NET Core](https://app.pluralsight.com/library/courses/building-graphql-apis-aspdotnet-core/table-of-contents?aid=7010a000002LUv2AAG)


Awesome! Please share it with anyone you think could use this information. Thanks for reading. As always, if you have any questions, comments, or concerns about this post, feel free to leave a comment below.