DEV Community

Cover image for Consuming GraphQL API In ASP.NET Core (Part 2)
John Ojo
John Ojo

Posted on

Consuming GraphQL API In ASP.NET Core (Part 2)

Here's the second part of the post HotChocolate: Introduction to GraphQL for ASP.NET Core (Part 1). 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 repository on GitHub.

Prerequisites

Create the Solution and Project

After opening VS, click the Create a new project link then search for Blazor and select it:
BlazorSearch

Give the project and solution a name GraphQLSampleAppUI then click create:
NameProAndSolu

Select the Blazor WebAssembly App option then click create:

Template

Install Dependencies

We will make use of GraphQL.Client(v 3.2.0) 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

Also, install the modernhttpclient and GraphQL.Client.Serializer.Newtonsoft packages respectively.

Consume The API

In part 1, to test the Query or Mutation, we used Banana Cake Pop:
mutation
query1

In this case, we will make use of the 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:

The way 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 in part 1, 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.

query{
  allDepartmentsWithEmployee{
    name
    employees{
      email
      name
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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:

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:

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

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:


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:

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:

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:

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:

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:

Running the Application

Ensure the GraphQL server 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

If you click the Employee link, you should get:

run2

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

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:

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.

Top comments (0)