Comparison Between GraphQL & REST API
This post is written by Jasbir Singh & Suvinay Pawa
Since 2000 REST (Representational State Transfer) which is based on accessing fixed data structures by a URL ( Endpoint ) has been the industry standard for developing backend services. This approach became inefficient with time as applications & software became more complex and various kinds of devices were developed. GraphQL, created by Facebook in 2012, is a database querying language which gives the client more control over the data it requires while being more efficient. It has a single endpoint that can be used to fetch and update data specified by the client using queries and mutations.
A question may arrive in your mind that whether GraphQL is the replacement of REST API, the answer to this question is that it’s an alternative. There are scenarios or use cases where REST API will perform better than GraphQL. In this article we will be comparing both of them, so we get an Idea of which API standard will be more useful in which scenario so we can design our backend services accordingly.
Why Facebook created GraphQL?
The main reasons for developing GraphQL have increased usage of mobile applications, sloppy networks, poor performance, difficulty in encoding query parameters in URLs, format & type of response to a query, and the requirement of efficient data fetching to make applications much reliable for user experience. Efficient data fetching is one of the most important reasons to develop GraphQL, sometimes on the client-side we only need specific data to be fetched from the server-side, but in REST API, we sometimes get additional data that is not required, which may take longer, therefore make data fetching slow and hence effects user experience. These are the main difficulties that Facebook had and they developed GraphQL. GraphQL minimizes the amount of data that needs to be fetched over the network and provides only the data required.
Rapid feature development is also an important point that made GraphQL more effective than REST API. Continuous and rapid development has become a standard for many companies. As Facebook started developing new and exciting features like News Feed. The complexity of the application goes on increasing and fetching and delivering data become more complex on both client and server-side.
GraphQL also provides a type system that is not present in REST API, which will be more useful as sometimes we can send wrong data to the server-side, which may crash our application without giving any warning or error.
Schema & Type System
GraphQL has types that define the data that can be queried on the server. Types are written in SDL (Schema Definition Language). Each key-pair value has a name and data type associated with it. This is auto-documented in the GraphQL interface which can be accessed via the browser. The client-side can use this schema to validate a query to make sure the server will be able to handle it. This gives immense control over the data to the client as it can choose and pick data as they require. If a query is made with a value, not in the schema, or if the backend sends data in a different format GraphQL will throw an error providing validation out of the box.
Since REST has multiple endpoints and each endpoint returns a fixed data format the Client has no control over choosing the data it needs. REST doesn’t have any built-in validation but npm packages like JOI which act as a middleware can be used.
Architecture & Operation
GraphQL is a powerful tool that allows you to make tailor-made requests reducing the computation required and preventing over fetching of data. GraphQL can be more useful when a monolithic backend is converted to a microservice architecture, it can communicate between multiple microservices, Legacy Systems, Third Party APIs to provide data at a single source.GraphQL requests also are HTTP GET Requests but operations like fetching and updating data are performed using queries and mutations. These queries can be nested for better efficiency. Another unique thing available in GraphQL is Subscription which is used for automatically receiving real-time data over time.
REST API is really simple — You have an endpoint and it can be used to access certain data, if there are X endpoints, they will provide X data sets, this is useful for small applications which don’t use a lot of services and require less amount of computation. In a REST API, we can perform various CRUD operations on a route using methods such as GET, POST, DELETE, PATCH to fetch, create, update, delete data.
Efficient Data Fetching
In this comparison, GraphQL beats REST API. Let’s understand it with an example. Suppose we are building a social media app like Instagram where we want to get comments on a post of a user. Refer to Figure 1, It shows a REST backend server, three backend endpoints for a user, post, and comments respectively, and a frontend application for making a request and getting a response from the server. In REST API the process to get comments will be as follows:
- First, we will request to get the data of the user.
2. Second, we will get all posts related to that user and find the required post.
3. Third, then we will be able to get comments on that post.
But the above can be easily done in one request using GraphQL. See below the given Image.
It shows a GraphQL server, with one endpoint “/graphql”, three queries to get posts, the user (id parameter is not required shown in ‘()’), posts by user id which contains comments. The Query to get comments can be nested in one query as
HTTP status codes
With suitable HTTP status codes, a health check on a given endpoint should give an idea about the API uptime status. A ‘200’ status code means that API is up and running, whereas a 5xx means something went wrong with the server. This is not the case with GraphQL since the monitoring tool has to parse the response body to see if the server is returning data or error. In this REST API has the upper hand over GraphQL. In REST API different HTTP status codes can help in analyzing and monitoring the API. REST API gives different status codes as ‘200’ for ok or success, ‘400’ for Bad request, and ‘401’ for Unauthorized and provides appropriate error messages respectively.
GraphQL on the other hand provides the status code of ‘200’ for ‘ok’ or ‘success’, but also gives the status of ‘200’ if there is an error like Bad request and Unauthorized, which makes analyzing and monitoring the GraphQL API difficult.
Caching of Data
Caching is built in the HTTP specification which REST APIs can leverage. In REST APIs, all the GET endpoints can be cached at the server-side. They can be cached by the browser as well and bookmarked by the client for frequent use.
GraphQL doesn’t follow the HTTP specification and is served over a single endpoint, usually (/graphql). Hence the queries cannot be cached in the same way as REST APIs.However, caching on the client-side is better than REST because of the tooling. Some of the clients implementing caching layers (Apollo Client, Relay) make use of GraphQL’s schema and type system using Introspection to allow them to maintain a cache on the client-side.
Conclusion
In my personal experience, GraphQL is a better choice because of the built-in validation, auto-documentation, and efficient queries but it does have some flaws as it doesn’t support uploading files or Web Caching out of the box although we can use libraries like Apollo that can handle this. It also has a steeper learning curve, but it is a very powerful tool for querying databases once you get used to it. REST has been around for a very long time due to which it has a very active community and multiple tools for analytics are readily available. Although GraphQL is my preferred choice for huge applications If the applications to be built are small REST would still be my preferred choice.