Building GraphQL APIs with ASP.NET Core

The consumer of a GraphQL API defines the data structure it want to receive in a query

First, let us see how a REST API works.

On the far right, there is data, for example in the form of a database, and there are entity classes. Each instance of an entity class represents one row of data in the table. An object-relational mapper like Entity Framework may take care of instantiating and populating these objects, but you don’t want to expose these entities directly. So they are converted to models or data transfer objects, objects that have a data structure that is easy to consume for clients, and maybe have some validation built in using attributes. Once you have the model, it’s the controller’s job to make it available to the outside world. There’s typically a controller for each type of model. For example, it could be a product controller, an order controller, etc. What controller is activated when a request comes in is determined by routing, which maps the URL to a certain controller, and all of these controllers react to HTTP methods. Each HTTP method triggers a different operation in the controller. A GET gets data, a POST introduces new data, etc. So there are typically quite a few controllers that have quite a few operations.

With GraphQL, there are typically no models, there is something called Schema. This Schema declares what a consumer of the API can access. The Schema also knows how to get the data. The API support GET or POST request, and there is always a query in the request.

Queries

  • Determines what happens in the API
  • Not tied to HTTP. HTTP is just a transport used to get the quert to the API
  • Downside: HTTP Caching: when using HTTP, because now each request is not at a unique URL anymore, it is now difficult to do HTTP caching.