La fabrique mobile Viseo Toulouse
logo

I have been interested in GraphQL for several months now, without understanding the functioning of this resource, due to the lack of time to really bend over it. So, I decided to take the necessary time and take the opportunity to share my discoveries with you.

In this article, I will explain what is a GraphQL? How is it different from REST? What are the advantages and disadvantages of the solution in an information system?

What is a GraphQL?

GraphQL is a Query Language originally used in 2012 by Facebook teams (the same ones who invented React). Originally, it was only designed by the company for internal use. In 2015, Facebook gave free access to the source code of GraphQL, at which time it managed almost all data access for mobile applications. Since 2017, this project has been available under OWFa-1.0 License (Open Web Foundation).

A growing community:

community

Today, GraphQL is used in production by many different companies such as GitHub, Twitter, Yelp and Shopify etc.

Where is GraphQL positioned in a software architecture?

GraphQL Server can be deployed by using any of the three methods listed below :

  • GraphQL server with connected database
  • GraphQL server that integrates existing systems
  • Hybrid approach
architecture

Image credits: GraphQL based solution architecture patterns

GraphQL is positioned as a middleware between the clients who request the data (mobile terminals, web browsers, etc.) and the owners of this data (third-party services, database, etc.).

In the above diagram, a GraphQL API acts as an interface between the client and the existing systems. Client applications communicate with the GraphQL server which in turn resolves the query.

A GraphQL server must support the following specifications :

  • Fetch: request to read data (read) A type of query used to request nested data from a data source (can be one or a combination of a database, a REST API or another GraphQL schema / server).
  • Subscriptions: for real-time queries (read) A type of request that customers can subscribe to it for a real time updates.
  • Mutations for entries: request to change data (write) A type of request using for writing / transferring data to the aforementioned data sources.

How is it different from REST?

To understand why GraphQL was designed, we must first go back to what doesn’t work in the REST APIs.

One resource = one URL

In a REST API, each resource requires a dedicated URL. For example, if the application wants to recover a user and their children, it will be necessary to make two separate requests.

A request to retrieve the user:

GET /user?id=100
// Réponse	
{
   id: 100,
   name: 'Alex',
   children: [365, 366]
}

A request to retrieve its children, from the returned data of the previous request.

GET /users?ids=[365,366]

// Réponse
[
   {
      id: 365,
      name: 'Lisa'
   },
   {
      id: 366,
      name: 'Bart'
   }
]

The breakdown by REST resource, forces us to multiply the service calls, and therefore to slow down the loading of the application.

loading.gif

To solve this problem, some backend developers have hijacked the principles of REST and return all the information in a single call.

GET /user?id=100

// Réponse :
{
   id: 100,
   children: [
      {id: 365, name: 'Lisa'}, 
      {id: 366: name: 'Bart'}
   ]
}

Certainly, this way doesn’t multiply calls, but it forces us to receive all the data, even if our application doesn’t need it. So, a REST API has no fields notion, it only knows resources.

Here's how GraphQL works

A GraphQL API allows you to retrieve only the desired fields on the desired resources, all in a single call:

// Requête:
POST /
{
    getUser(id: 100) {
        name,
        children: {
            name
        }
     }
}

// Réponse :
{
   name: 'Homer',
   children: [
      {name: 'Lisa'}, 
      {name: 'Bart'}
   ]
}                                                 

In the query above, we are asking for the user with id 100, with their name and the name of their children. We must indicate in the request the information that we are needing.

How to create a graphQL query?

The GraphQL endpoint : The REST API v3 has numerous endpoints; the GraphQL API v4 has a single endpoint:

https://parseapi.back4app.com/graphql

The endpoint remains constant no matter what operation you perform. The two types of allowed operations in GraphQL API are queries and mutations.

Queries are structured like this:

query { JSON objects to return }

query

For a real-world example, see "Example query."

What characterizes GraphQL?

  • A hierarchical structure: Execution of more complex queries in a single query. 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.
  • Graph databases.
  • Strong typing: Able to automatically check whether a request has been correctly formulated. Error messages with clear explanations.
  • Great flexibility: Very great freedom and a lot of flexibility in terms of development, even adaptation of your interface

GraphQL vs Rest?

What are the advantages and disadvantages of GraphQL?

Would you like to try GraphQL in a business or corporate environment? Be aware that it has both advantages and disadvantages.

Advantages:

  • Development speed
  • A GraphQL schema defines a single source of truth in a GraphQL application. It allows a company to federate all of its API.
  • GraphQL calls are managed by a single round trip. Customers get exactly what they asked for, nothing more.
  • GraphQL is introspective. A client can request a list of the types of data available. This function is very useful for automatic generation of documents.
  • GraphQL allows you to upgrade the API of an application without degrading existing requests.
  • GraphQL doesn’t impose a specific application architecture. It can be implemented on an existing REST API and work with existing API tools.

Disadvantages:

Like everything in this world, the use of a new tool induces new problems:

  • Developers who usually work with REST APIs will need to learn how to use GraphQL.
  • GraphQL makes the workload of a data request difficult for server developers.
  • The number of server-side requests induced by GraphQL Lazy-loading can explode. This can impact the performance and requires looking for optimizations.

Conclusion

GraphQL is a very practical tool that could take your application to the next level, by strengthening it and making it more predictable. Although it seems quite complex in the beginning, in reality the handling is quite good and easy, especially thanks to the Open Source tools like Apollo or Prisma.

If you never gave it a try, you should. All the cool kids are doing.

If you want to know more about GraphQL vs REST you can check this Medium post.

Tagged with: