An Introduction To GraphQL
GraphQL
19/09/2022
GraphQL is described as a query language for your API, but what exactly does that mean? To get a deeper understanding of this succinct description, let me explain why it was created in the first place.
The problem it solves
Before GraphQL, Representational State Transfer (REST) was the 👉 de facto architecture for APIs on your server. However, as time went on, it became unsuitable for most modern web development needs and caused 2 major issues known as under-fetching and over-fetching.
Let's illustrate these issues with an example. Assume you have two endpoints:
/directors/:id
returnsid
,name
,age
,biography
andmovieIds
given a specific director id./movies/:id
returnsid
,title
,description
,rating
anddirectorId
given a specific movie id.
Under-fetching
To display information of a 🎬 director and all his movies, we would first need to fetch that director from the directors
endpoint (e.g. /directors/14
). Subsequently, we would then need to fetch each movie seperately that is listed in the movieIds
property. Assuming it's only 1 movie, that's already 2 requests in total. But if it's an industrious film maker like Spielberg, there will be many more.
In this sense, the client side is under-fetching, as in not getting enough data in a single request.
Over-fetching
Over-fetching happens in the sense of receiving unnecessary data on each request, as each endpoint gives a predefined structure of data back. For instance, you might not care to show the description of each movie in the authors page, but only the title and rating.
Together, these issue can be noticeable and painful on low performance devices 📲 and slow bandwidth.
GraphQL approach
Knowing these issues, Facebook developed a more efficient alternative that would allow you to fetch only the resources you asked (i.e. queried) for in a single request. This is done by structuring your request in the form of a graph, also known as the Graph Query Language.
query DirectorInformation { director(id: 14) { name age biography movies { title rating } }}