In this article, we are going to discuss the API Development in .NET with GraphQL. What is GraphQL? How to set up GraphQL in .NET application.
APIs allow software to speak to each other. Currently, the dominant design model is REST. Though it is known to build long-lasting APIs, it has issues that come with today’s applications, especially with the rise of mobile app consumers. Queries done with REST require many HTTP endpoints that return fixed data structures which can easily result in excess data. Issues come also with frequent updates to the applications since knowing what individual clients need is very difficult.
What is GraphQL?
GraphQL was built by Facebook in 2012 (publicly released and open sourced in 2015) for their mobile and web apps. It was designed precisely for the need for more flexibility and efficiency in the client, server communication.
GraphQL has one “smart” endpoint that can take complex operations and return only the data the client needs. It is an open-sourced framework for the development and deployment of server less GraphQL back ends. GraphQL is a data query language for APIs and runtime for fulfilling those queries with your existing data https://graphql.org.
GraphQL was created to solve the issues of the times APIs, especially with over fetching. This was caused by the basic structure of the queries, causing a series of requests with excess data. This is especially an issue with mobile apps that are used with devices and network conditions that can´t handle huge 9 amounts of data and payloads. Today it is maintained by a vast community across the globe consisting of both companies and individuals (Howtographql.com).
Let's start with step by step implementation in ASP.NET Core 2.0.
- Open Visual Studio 2017.
- File -> New -> Project.
- Select ASP.NET development services for Web Application -> Provide SolutionName “GraphQLAPI”, click OK.
- Select the Web API template as the following screenshot:
- Click Ok
Now, what next your Web API project is created now time to setup the GraphQL in that API project using following steps:
- Open NuGet Package Manager from Tools.
- Click on Browse tab and search for ‘GraphQL’ package.
- Select the first package and click Install, it takes only a few minutes to install.
Next, set up the models for our API, create a new folder called “Models” and add “Book” and “Author” models into that.
And now, we need to create a “Data” folder, and add “IBookRepository” and “IAuthorRepository” interfaces into that.
- > GetBookssAsync();
- > GetBooksWithByCategoryIdAsync(int categoryId);
- > CategoriesAsync();
Let’s implement “IBookRepository” and “IAuthorRepository” interfaces with a few sample data like as below.
The most basic components of a GraphQL schema are object types, which just represent a kind of object you can fetch from your service, and what fields it has.
Now we will create two ObjectGraphType into the “Models” folder, and these are “BookType” and “AuthorType” classes.
Let’s create a root type to use the query operations. For that, create a new class called “LibraryQuery“.
Next, can create the schema which will describe the structure of the data.
The Query and Mutation types
There are two types that are special within a schema:
First one is to prepare GraphQLendpoint, another one is to perform service injection operations. So, let’s create a request class called “GraphQLRequest” into the “Models” folder as below.
After creating the request object, we can prepare the controller. Therefore, create a “GraphQLController” class as following below.
Now, the last thing is the dependency injection. Let’s inject the services in the “Startup” class as follows.
Finally, we created the setup the API application development with GraphQL. Last steps to test this created API using the Postman or you can use Swagger as well to test.
If you don’t have the Postman chrome extension, you can install this chrome extension using following link:https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en
Following are the steps to test the API application:
- Run the created API application using the Run button or press ‘F5’.
- After successfully build the application open in new window of your browser as per browser selection in your visual studio my is chrome.
- The above screenshots shows your application is running with default values controller just copy the URL as follows(after replacing with the values controller name with our newly created controller name i.e. GraphQL);
- Copy the above your(Note: Here my port is 2706 in your case it might be different) URL and paste it in Postman as follow:
- Set the action POST and Headers as below screen shot:
- Now time to create the request object, for that move to the next tab after the Headers – Body tab and select raw radio button. Create the request as below screen shot:
- Finally, all set up is done time to featch the data, for that click on blue color button ‘Send’ and you can see the output as below screen shot:
- If, I want to fetch the record of author with id=1 for that see below screen shot:
- Next, I want the all the books written by Author id = 1 for that see below Request:
I hope that beginners, developers, understood the concept of GraphQL, What is GraphQL? API Development in .NET with GraphQL. If you have any suggestion regarding this article, then please contact me.
“Learn It, Share it.”