GraphQL is the technology created by Facebook that enables the frontend to negotiate with the backend for the data it wants.
GraphQL is a client-side query language coupled with a pattern — formally known as a “schema”. It allows for content negotiation which means you will only have one endpoint. It also allows you to query for exactly the fields you want.
The limitations of the current REST APIs
Multiple Endpoints : When we need to implement the RestAPI some times it needs multiple endpoints to consume the new features.
Over fetching: When more data is delivered upon fetching than is required. In these cases, you’re unable to utilize all of it.
Under fetching: When the data you get back is not enough. Often times, the data is so little that you have to run another query.
These limitations are overcome with the help of GraphQL
Setting up GraphQL in .Net Core
We will need to do the following
- Create a new solution
- Create an ASP.Net Core Web Application with API
- Install the GraphQL NuGet package
GraphQL consists of a schema definition, besides the schema, there is a central concept called resolvers. A resolver knows what to do with an incoming query. A resolver is mapped to a certain resource.
To query a resource you would type :
If you need to specify more fields you want under the resource like :
The end result is always a JSON response it matches your query.
Example of a Query with a parameter is given below: