Image for post
Image for post

The purpose of this blog is to demonstrate how to create an ASP.NET Core 2 project that implements GraphQL. This blog goes beyond a hello world example and fully implements concepts such as: POCO classes, interfaces, dependency injection, adapter pattern, ASP.NET Core 2 Web App, GraphQL.NET, GraphiQL and some JavaScript libraries(Node and React). See Demo

There are multiple sites with tutorials on how to start working with GraphQL. The problem that I found is that they were mostly oriented to JavaScript development and also they were very simplistic. By the end of this tutorial, you should be able to play with real data coming from an static repository that you can later replace with your own implementation connecting your database or even your own microservices. Keep in mind that, I will focus mostly on .NET development instead of JavaScript. So, I will welcome any comments or suggestions on how to improve my JavaScript on these examples.

What is GraphQL? GraphQL is a language that sends a JSON string to the server and returns a JSON response back to the client. GraphQL represents a different paradigm in API development where we focus on the client first. Some of the main features include:

  • Defines a data shape: We know exactly what we will get in our responses because we define that in our request. On the contrary, REST services where we get a response with all the available fields in a data contract.
  • It is hierarchical: A more natural way to create object relationships. Later, we will call sales order. An order is related to customers, employees, providers, products, and order details. A client can obtain all of that data at once and on demand. On the other hand, a client would need to call multiple endpoints to get all data required for a Sales Order.
  • It is strongly type: We can define schemas, types, queries and more.
  • It is introspective: It is very easy for developers to explore and learn the API.

GraphiQL is A graphical interactive in-browser GraphQL IDE

First we need to create our GraphQL implementation in the server. Then we can use GraphiQL to interact with our GraphQL data. However, clients can also use other IDEs such as Postman. Same as in REST APIs, clients can connect to the server and perform HTTP requests to the GraphQL server.

Enough with definitions and let’s get started with some code! We will create functionality to interact with Sales Orders. The following diagram shows the relationship among the data objects that we will create. Feel free to improve it and add more properties as needed but I wanted to keep it simple enough to represent hierarchical relationships.

Image for post
Image for post
Figure 1 : Sales Order Entity Relationships
  1. Create new .NET Core 2 Class Library for the data objects related to our new Sales API. The name of my new library is Sales.Data. I will display a few data objects but you can see the full code here.

2. Create new .NET Core 2 library for repository layer to include our business logic implementing the ISalesService. I will create a static repository but you can create other implementations as needed (connecting to database or your microservice). See full code here.

3. Create new .NET Core 2 Class Library for the data objects related to GraphQL. My library in my demo is called GraphQL.Data. See full code here.

An order that contains relationship to customer, employee and order details
An order detail contains relationships to a product
A product is related to a product category and a provider
  • Create Query to include the Types.
A query contains all available Types that will be exposed
  • Create the Schemas to include the Queries. Notice that use dependency injection and a adapter pattern to implement IDependencyResolver. Also, this demo only works with queries (getting data). However, we could also include mutations (adding data).

4. Create .NET Core Web Application — API (Core 2) called GraphQL.API

  • Add reference to the schemas library: GraphQL.Data created on step 3
  • Add reference to Sales.Repository created on step 2
  • Delete Controller folder and any of its content. We will not be using the default ApiControllers. We will use implement our custom middleware.
  • Add nuget package to the library for the latest GraphQL for .NET by Joe McBride
  • Modify the GraphQL.API csproj file to have the AspNetCore.All version that your host provider supports ( this can be an issue if not set properly). My hosting provider supports up to version 2.0.3.
Modifying the Microsoft.AspNetCore.All version to match your hosting provider
  • Create the GraphQL Request object
  • Create a file to contain GraphQL Settings
  • Create Middleware to handle the GraphQL request. I am taking this (MIT) code from GraphQL.NET
  • Create a folder called “public” inside the GraphQL.API project. Add the 3 files inside this folder (This is front-end development and beyond the scope of this blog).
  • Modify the Startup file: Add dependency injection on ConfigureServices method and modify the Configure method to include our custom middleware
Notice that we MUST add a singleton for every existing GraphQL Type,Query and Schema.
  • Modify the Program file to include our public folder
  • Open launchSetting.json from Properties and remove any launchUrl key-value pair. The API template include some extra settings that we do not need. We need to remove them to use our custom middleware as define on Startup file.

5. Go to the solution folder

  • Install latest Node if you have not installed it yet in your computer
  • Add a folder called “app” and include these files in there. The app.js contains React.JS that sets up your GraphiQL.
  • Add files to your solution folder for GraphiQL: Package.json (contains JavaScript dependencies), (bash to restore your API project), Webpack.config.js (sets required dependencies on JavaScripts and style sheets), and .babelrc file. There other ways to install these, but this is again to eliminate complexities on explaining front-end development.
  • Open command prompt pointing to your solution folder
  • Type “npm install” and hit Enter
  • Type “npm run webpack” and hit Enter
  • Using Visual Studio, set API project as startup and run it

By now, you should be able to see a GraphiQL with your Sales Schema. Feel free to test it around. Copy and paste the following on your GraphiQL page (left side):

Image for post
Image for post
GraphiQL from left to right: our custom query, the results from our API, and the documentation. See Demo

One of the things I like about GraphQL is that we only load data (in memory data here but it could have been data from database) that we need. We are not loading all data from our repo and then filtering it to display only what the user wanted. Place a break point on your repository, modify your query on your browser (GraphiQL) to include or not any children relationship. You will see that we only can children when we need them.

You can also use the directives “@include” or “@skip” to tell the browser that you want to include or exclude any child.

There are other subjects to consider such as caching and authorization. It is recommended to use your business layer to implement these good practices. I have see some articles that implement authorization using front-end development. However, I recommend you to rely on your hopefully existing authorization process (i.e. OAUTH 2, OpenId, etc.)

Written by

A passionate software developer eager to learn, evaluate and share!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store