Photo by Vadim Bogulov on Unsplash
In order to best understand what GraphQL is we first need to understand where we are coming from. When you want to programs to talk to each other you first need to agree on a common standard for the communication.
There are many different standards for communication but one of the most common during later year has been what is called a REST-api. The acronym stands for “Representational State Transfer” and the focus for a REST-api is to avoid that programs need to take into consideration how the other program works internally.
What you do is creating an api with so called "resources" where each resource has its own url that can be called with different methods such as "POST", "GET" or "DELETE". To make it less abstract we can take a hypothetical example where we created a service for a todo-list. In this service you can send a POST-request that contains for example "Buy milk" to example.com/todo-list and this request will create a new todo containing "Buy milk".
So then why do we need GraphQL?
This sounds easy and good so why would we need GraphQL? If you only have a small number of resources and always need the same type of information then a REST-api works without any problems. The issue comes up when you have many different resources and you need different information in different parts of the application or on different devices. An example would be that you have a webapp and a mobile app and the mobile app needs less information because you don't shown the exact same information as on the web.
There are several solutions to this problem. The easiest solution is to just show less information on the mobile device than on the webapp even if you get all the information from the REST-api. The downside with this solution is that you send more information across the network than needed that will make your application slower than it needs to. Another possibility is to send arguments with your REST-api call that tells the server what information it should return. The downside with this is that your server then needs to understand what each argument means and how to handle this which makes it less independent from the client application.
GraphQL solves this problems by providing just one endpoint for all requests where the client can specificy exactly what type of information that it wants the client to send back. Then you can have a standarised way of telling the API exactly what information it needs to send back and you avoid the problem of sending information that is not needed. A GraphQL request to an api for a todo-list app can look like this:
query {
todo {
allTodos {
id
name
date
}
}
}
And lets say you don't need the date on another request then you can easily modify the request and only get the information that you need. You can do that by just removing "date" from the request like this:
query {
todo {
allTodos {
id
name
}
}
}