Back
Tech 6 min read - 21 Feb. 20 - Bastien Landry

Short introduction to GraphQL

What is GraphQL? Or rather, let's start with the question, what is GraphQL not? Despite its name, GraphQL is not an alternative database to MySQL, nor a competing language to SQL. In fact, GraphQL is a query language for APIs. If we take a brief history of the different ways data has been sent and received over time, we can distinguish three phases: the Stone Age, the Bronze Age, and the Iron Age.
In our small analogy, the Stone Age corresponds to the SOAP protocol. Specifically, SOAP APIs send data in XML format, generally using the HTTP protocol (but not necessarily). The real problem with SOAP is the verbose aspect of the requests; the format is heavy and unsuitable for current issues. A solution had to be found by moving to the Bronze Age, the REST API. In this case, REST is not a protocol (unlike SOAP) but rather a set of rules and constraints to be used to establish a minimum of coherence and interoperability on the internet. REST exclusively uses the HTTP protocol and generally communicates via a JSON format. Like Monsieur Jourdain in Le Bourgeois gentilhomme who spoke prose without knowing it, many have ultimately used REST without knowing it, for example, by setting up a simple Node.js server. REST's main drawback is also its main advantage, its malleability. There's no real standard followed by everyone, and it can quickly turn into a free-for-all! We therefore had to evolve towards the Iron Age. The Iron Age is GraphQL.
We won't spend too much time on theory, but it's important to understand that unlike others, GraphQL is a language; it's a simple and elegant way to make requests to the server. GraphQL uses the POST method of the HTTP protocol and, unlike REST, it only uses a single route. GraphQL only needs one endpoint. To better understand all this, we're going to create a small website using REST on the one hand and look at how we could adapt it with GraphQL.
Our site will focus on the mysterious people of the Galadrim, a people of elves from the Lord of the Rings. This people lives in the forest and builds treehouses as homes. In our world, each elf can also have friends and a home. If we want to build a database from this information, we would need:
  • elves : elfId (Int), name (String), age (Int), houseId (Int)
  • houses : houseId (Int), surface (float), woodType (enum)
  • friends : friendId (Int), firstElfId (Int), secondElfId (Int)
In addition to that, we're going to set up a very basic Express server (see https://expressjs.com/fr/starter/hello-world.html if needed). The goal is to send an elf's information to the front-end on a page: their name, age, the characteristics of their house, and also all their friends. For the front-end part, we're going to use create-react-app (https://github.com/facebook/create-react-app).
Here's what our page should look like:
GraphQL (1)
We can distinguish 4 parts:
  • My personal information
  • The surface area of our house and the type of wood used
  • My friends list
  • My friends' friends list
With REST
Technically, using a REST API, we would need to make the following calls:
  • GET /elfe pour récupérer les données de mon elfe
  • GET /house pour récupérer les données de ma maison
  • GET /friends pour récupérer l’ensemble de mes amis
  • GET /friends?elfeIds=[1,4,8] pour récupérer les amis de mes amis
Technically, we could make all these requests in one go, but this would be specific to this page and our entire API would become case-by-case. This isn't really good practice as it greatly complicates code readability and API comprehension for a developer, who would deal with a multitude of specific endpoints. Also, to preserve the cleanest and simplest architecture, it's probably more logical to make 4 consecutive API calls.
With GraphQL
With GraphQL, there's only one call:
  • POST /graphql
Indeed, GraphQL is a language, and so the entire subtlety lies in the content (body) sent with the request. This content follows a particular format and is interpreted by our back-end. Here's what our body looks like:
carbon (8)
Let's try to dissect the content:
  • The word 'query' refers to the type of request we make to GraphQL; we distinguish two types, query and the types mutation. A query requests data from the server, a mutation makes a modification, for example, a database insertion. Here, we are requesting information, so we are making a query type request. There is also another type, called subscription, but we are not using it here.
  • The word 'initialization' isn't very important; it's the name I gave to my query; you could have put anything, 'legolas' for example, and it would have worked!
The word 'elf' however is important; it refers to the query that I'm going to use. Let me explain: when I create my GraphQL API, I will have to write it a representation of my database so that it can understand the attributes of each, the relationships, etc. My query will look like this:
carbon (6)
We will therefore ask it to return an elf for an elfId passed as a parameter (in our case, elfId is 1). We then use a resolver that will go and fetch my information. To put it simply, a resolver is a function that retrieves data from the database, for example, via an SQL query. 
  • The type Elf that we define in our query therefore has all the attributes we need: a name, an age, a house, and friends. The getElfeForId resolver will therefore use other functions itself to retrieve what we need from the database. 
The Elf type we are talking about is defined as follows at the back-end level:
carbon (12)
It's important to understand here that there's no magic at this level; you have to explicitly make SQL requests to then produce the Elf object we expect. Thus, the functions getHouseForElfeId and getFriendsForElfeId are ultimately SQL requests. In GraphQL, fields have types; these types can be primitive like integers (GraphQLInt) or generated types like the Elf type. Thus, you can return an object or a list of objects (using GraphQLList) as a field. Also, with the definition of the Elf object we made above, the friends field expects to return a list of elves!
So, there's a lot of upfront work to do, but once it's done, there's no need to touch the back-end, no new routes to create, etc.! Everything then happens with the front-end, which can ask our API for what it needs. If, for example, on a page we only need the elf's name, our request will look like this:
carbon (9)
No work is needed on the back-end; everything is already prepared. So we can make a shopping list of everything we need at the right time!
That's the essence of GraphQL in a few lines. It's important to highlight that GraphQL brings a significant standard and ease of use. Besides the practical aspect, GraphQL's error handling makes its implementation simple; if something goes wrong, GraphQL will tell us quickly! Some might wonder how to manage read and edit permissions; for that, we'll need to use the notion of context ! Many aspects of GraphQL can be explored in more depth (and perhaps will be in a future article?), but the idea of this article is to present the need and the solution offered by GraphQL.

Do you want support to launch your digital project?

Submit your project now