Uncategorized

GraphQL: The new standard for APIs

WHAT IS GraphQL ?

GraphQL (Graph Query Language) is a new API standard that is a more powerful, flexible and efficient alternative to REST. It was developed by Facebook and is now maintained by a large community of individuals and companies around the globe.

At its core, GraphQL provides declarative data fetching where a client can specify what data it needs from an API. Instead of multiple endpoints that provide fixed data structures, a Graph QL server only exposes a single endpoint and responds to queries with precisely the data that the client asked for.

So let us see for ourselves, how does it all work.

A Query language for APIs

Most applications today have the need to fetch data that is stored remotely elsewhere in a database that is accessible over the internet. This is why web servers are used. Whenever a client wants something that it wants to display to the user, it sends a request to the server. The server is programmed in a way that it can respond to the request by retrieving required information from the database and send it back as a response to the client.

Before we dive deeper into the technical concepts, we should understand the history behind the evolution of REST APIs.

A more efficient alternative to REST

REST has been a popular way to expose data from a web server. When REST APIs came into being, the client applications were relatively simple and the development speed wasn’t nearly where it is today. As a result, REST was a good solution for many applications. However, the API landscape has radically changed over the past couple of years, and there are 3 main factors that are proving to be a challenge for the APIs and how they are designed.

  1. Increased Mobile usage, low power devices, and sloppy mobile networks create a need for efficient data loading. These were the initial reasons why Facebook developed GraphQL. GraphQL minimizes the amount of data that needs to be transferred over the network, and thus majorly improves applications that operate in such conditions.
  2. The heterogeneous landscape of front end frameworks and platforms that run client applications make it difficult for one API to serve all clients. Using GraphQL, every client can request and fetch only the data it requires.
  3. Fast development speed & expectation for rapid feature development. Continuous deployment has become a standard everywhere and frequent product updates are indispensable. With REST API, how the data is being exposed by a server, often needs to be modified to account for specific requirements and design changes on client-side. This hinders fast development practice and product iterations.

Now that we have a bit more perspective about REST, let us understand the history behind GraphQL and its evolution.

GraphQL’s evolution

Facebook started using GraphQL in 2012 in its native mobile apps. Interestingly, GraphQL has been largely popular with web technology and has gained little traction with mobile apps. The first time Facebook introduced GraphQL publicly was at react.js conference in 2015, and shortly after that, they announced their plans to opensource it.

Because Facebook always used to speak about GraphQL in the context of react.js, it took a while for non react developers to understand that GraphQL was by no means a technology to be used only with React. Instead, GraphQL is a technology which can be used anywhere where a client is communicating with an API.

Parallel to Facebook, other companies were also working on similar ideas to make API interactions more efficient. Netflix open sourced their solution Falcor and Coursera eventually cancelled their solution and switched to GraphQL.

As of today, the GraphQL community spans over entire globe with several companies and thousands of developers. Some of the companies actively contributing and using GraphQL are –

There are dedicated conferences for GraphQL like –

Then there are online resources like GraphQL radio podcast and weekly newsletter that keep you updated with what’s happening in GraphQL world.

GraphQL is the better REST

Over the past decade, REST has emerged as the standard for designing web APIs. The best ideas in REST are believed to be that of stateless servers and structured access to resources.

On the other hand, one major downside has been – REST is a strict specification, but the concept was wildly interpreted, and almost all APIs are called RESTful even though they do not follow REST guidelines. Also, REST APIs have shown to be too inflexible to keep up with the rapidly changing requirements of the clients that access them.

GraphQL was developed to cope with the need for more flexibility and efficiency. It solves many of the shortcomings and inefficiencies that developers experience when interacting with REST APIs.

To illustrate the major differences between REST and GraphQL when it comes to fetching data from an API, let’s consider a simple example scenario: In a blogging application, an app needs to display the user’s first name, titles of all the posts that user has ever created. The same screen also displays the names of the last 3 followers of that user. We will see one by one how REST and GraphQL tackle this requirement.

REST Solution – Dedicated Endpoints for each requirement

With a REST API, we would gather the data by accessing multiple endpoints. There could be /users/<id> endpoint to fetch the initial user data.

Response

Secondly, there’s likely to be a /users/<id>/posts endpoint that returns all the posts for a user.

Response

The third endpoint will then be the /users/<id>/followers that returns a list of followers per user.

Response

As we saw above, we have to make 3 different requests to 3 different endpoints to get sufficient data to show on the users’ profile page. You’re also over fetching since the endpoints return additional information that’s not needed.

GraphQL solution – One Endpoint for all requirements

In GraphQL, we simply send a single query to the GraphQL server that includes the concrete data requirements. The server then responds with a JSON object where these requirements are fulfilled.

Using GraphQL, the client can specify exactly the data it needs in a query. Notice that the structure of the server’s response follows precisely the nested structure defined in the query.

It is evident from the above demonstration that GraphQL APIs are more flexible, powerful and easy to maintain. The main benefits are

  1. It eradicates the need for Overfetching and underfetching. Overfetching is when a client downloads more information than is actually required in the app. Imagine for example a screen that needs to display a list of users only with their names. In a REST API, this app would usually hit the /users endpoint and receive a JSON array with user data. This response, however, might contain more info about the users that are returned, e.g. their birthdays or addresses – information that is useless for the client because it only needs to display the users’ names.    Underfetching and the n+1 problem –  Underfetching generally means that a specific endpoint doesn’t provide enough of the required information. The client will have to make additional requests to fetch everything it needs. This can escalate to a situation where a client needs to first download a list of elements but then needs to make one additional request per element to fetch the required data.
  2. Rapid modifications to the product, front end views and APIs as a result – With REST APIs, whenever there is a change to the frontend view or design change of the product, the APIs need to be re-tuned to match the data needs of the views. With every change that is made to the UI, there is a high risk that now there is more (or less) data required than before. Consequently, the backend needs to be adjusted as well to account for the new data needs. This kills productivity and notably slows down the ability to incorporate user feedback into a product.                                                  With GraphQL, this problem is taken care of. Since a single GraphQL API endpoint is hit with an appropriate query, and clients can specify their exact data requirements, the backend does not need adjustments when the design and data needs on the frontend change.
  3. Reports and usage Analytics of backend –Since each client asks for specific data set from a GraphQL API, it is possible to gain crucial insights of data being used and help to evolve the API by adding/deprecating the fields as required. Low-level performance monitoring of the requests that are processed by your server is also possible. The concept of resolver functions is used to collect the data that’s requested by a client. Measuring the performance of these resolvers provides valuable information about the issues in the system.
  4. Benefits of a Schema & Type System – GraphQL uses a strong type system to define the capabilities of an API. All the types that are exposed in an API are written down in a schema using the GraphQL Schema Definition Language (SDL). This schema serves as the contract between the client and the server to define how a client can access the data. Once the schema is defined, the teams working on frontend and backends can do their work without further communication since they both are aware of the definite structure of the data that’s sent over the network.

 

Core concepts of GraphQL

Now we will learn about the fundamentals of GraphQL. These are Schema, Queries, Mutations and Subscriptions.

Schema definition language

GraphQL has its own type system that’s used to define the schema of an API. The syntax for writing schemas is called Schema Definition Language (SDL).

Here is an example of how we can use the SDL to define two simple types called Person and Posts.

This type has two fields, they’re called name and age and are respectively of type String and Int. The ! following the type means that this field is required.

We can also have another type called Post to show all the posts from a person. For this purpose, we declare a type post and add a relation to Person type. This shows that every post will have an author with type Person.

Now, we add the post field to person type to express that a person may have multiple posts.

Note that we just created a one-to-many-relationship between Person and Post since the posts field on Person is actually an array of posts.

Queries

In GraphQL, the structure of the data that’s returned is not fixed. Instead, it’s completely flexible and lets the client decide what data is actually needed. That means that the client needs to send more information to the server to express its data needs – this information is called a query.

Here is an example query that the client sends to a server

Or, you could query nested information too, like posts from each user

The allPersons field in this query is called the root field of the query. Everything that follows the root field, is called the payload of the query. This query would return a list of all persons currently stored in the database with their names, age and title of all their posts.

Queries can also have arguments to modify the request, for example, if we wish to fetch only the last 2 persons

Mutations

Many times, in addition to requesting information from API, we also need to modify the data that is stored in the backend. In such cases, mutations are used. There generally are three kinds of mutations – creating new data, updating existing data, deleting existing data.

We write mutations same as queries, but they always start with keyword “mutation”. For example, to create a person

Here root field is createPerson, and payload specifies two properties name and age. The server response example for the above mutation is

Subscriptions

For any application, it is vital to get updates for important events happening on the server and to be able to take actions on client-side accordingly. For this purpose, GraphQL introduced the concept of Subscriptions.

Whenever a client subscribes to an event, it will start and hold a steady connection with the server, and when the event happens, the server pushes corresponding data to the client. Unlike queries and mutations, where a request-response cycle is followed, subscriptions represent a stream of data sent over to the client.

Here is an example where subscribe to the events happening on a person type

Whenever a mutation creates a new person, the server sends data about this new person to client

Writing a Schema

All that we have learnt so far about types, queries, mutations and subscriptions come into play when we start writing schemas. Schema is the most important concept in GraphQL. It specifies the capabilities of the API and defines how clients can request the data. It is often seen as a contract between the server and the client.

Generally, a schema is simply a collection of GraphQL types. Putting together what we learnt so far, here is the schema for all queries, mutations, and subscriptions for our API

Conclusion

GraphQL is essentially a specification, a document which instructs how the server should be designed to behave as GraphQL server. It instructs what kind of requests should be handled by the server, and what the response format for these requests should be. To read about the specification, go to https://facebook.github.io/graphql/

When you start out on building a GraphQL based solution, you have to start by building your GraphQL server from scratch. You can use one of the available reference implementations for it. But you can also use a service like https://www.graph.cool/ that provides a powerful GraphQL server out of the box.

To learn further in detail about GraphQL, go to https://graphql.org/

About The Author