What is GraphQL?
It is a query language for the API in simple term. But what actually means and how it helps is a whole bunch of talk.
GraphQL is a syntax that describes how to ask for data, and is generally used to load data from a server to a client. GraphQL has three main characteristics:
- It lets the client specify exactly what data it needs.
- It makes it easier to aggregate data from multiple sources.
- It uses a type system to describe data.
With GraphQL a user an make a single request and take all the data from the back-end rather than making a lot of request and it drastically reduce the server requests and improve performance. Below a sample query and the response.
# Query
{
hero {
name
}
}
# Response
{
"data": {
"hero": {
"name": "R2-D2"
}
}
}
Difference between GraphQL and REST API
For the past few decades we are using REST APIs and it was completely fine. But let’s see how it works.
In REST API there are specific endpoints for every resource that it needs and a client sometime have to make several requests to get a the actual data and also the data is sometime overloaded and sometime under loaded.
And the data is also store in different tables so you have to make different queries for different tables.
E.G. –
- The YouTube page there are whole bunch of videos that comes up and in a REST architecture the YouTube make a request to the server to get all the IDs.
- And then it again request back to get all the information about all the ID.
- So for a million user the REST architecture is sending 2 request for this simple task.
But in a GraphQL architecture the data will comeback in a single request and there will also be specific.
The GraphQL has only one endpoint “/graphql”.