Knowledge Hub
For manager
Headless CMSFor developer
Web FrameworksStatic Site GeneratorsServerless DatabasesMonoreposHostingPIMLearn
GuidesTutorialsAdopt
Case studiesAddressing the ongoing API debate about whether to choose GraphQL or REST, we set out to break down both options in a thorough comparison article. First, we go into the main definitions of GraphQL and REST APIs and then, you will find out:
The battle between GraphQL vs REST has been ongoing for quite some time. Primarily, because these two API styles have a different approach when dealing with the transfer of data over internet protocols.
Creating an Application Programming Interface(API), used to be limited to deploying and consuming.
Now, as the API universe is expanding, a lot goes into building it: right from the design phase all the way up to the final release. One of the major aspects to consider while designing an API is the architecture that is appropriate to fit the needs of the business. When building and consuming an API, developers are usually faced with a dilemma as to which is the right architecture to choose: REST API or GraphQL.
While REST API may seem like the de-facto option for API creation, GraphQL has gained momentum due to its high adoption rate, and is now seen as a revolutionary alternative to REST API. Before diving deep into the differences between GraphQL vs REST API, as well as their pros and cons, let's first understand what they are and their mechanisms.
REST(Representational State Transfer) is an architectural style that conforms to a set of constraints when developing web services. It was introduced by Roy Fielding as an alternative to the complex method of SOAP (The Simple Object Access Protocol) in the year 2000 while presenting his Ph.D. dissertation.
RESTful API is a Web Service API that follows the REST standards. Unlike SOAP, a REST API is not constrained to an XML format and can return multiple data formats depending on what is needed.The data formats supported by REST API include but are not limited to:
When a client calls a RESTful API, the server transfers the representation of the state of the resource to the client in a standardized representation. REST API works by returning information about the source that was requested by the client. This information is then translated into a format that is easily interpreted by the client. Through REST API, clients can modify or add new items to the server.
A REST request is made up of four essential parts:
An endpoint contains a URI (Uniform Resource Identifier) that helps in identifying the resource on the internet.
An HTTP method describes the type of request that is sent to the server. They are:
When working with data, a RESTful API uses HTTP methods to perform CRUD (Create, Read, Update and Delete) operations.
Headers
provide information to client and server usually for authentication purposes.
A body contains information that a client wants to send to a server, such as a piece of data that needs to be added or replaced.
What are some REST constraints to consider when designing a REST API?
Although the REST API is a simple interaction system that efficiently performs operations and returns data via HTTP protocols, we need to keep in mind that not all HTTP APIs are REST APIs -- as there are different kinds of API types. The following architectural requirements need to be taken into account while considering REST APIs. The six constraints are:
For example, a client downloads a Java applet or a JavaScript code from the server.
However, this constraint has its own risks as you could download code from an unreliable source thereby compromising on your security level.
REST API Example:
To have a better grasp of the concepts of REST API, let’s take a look at the base url of the Rick and Morty API: https://rickandmortyapi.com/api
The Rick and Morty API has three available resources e.g:
Suppose a client needs information about the name and state of a character, then the server creates the representation of a resource and responds back to the client in a data returned in json format.
With REST, the endpoint looks like this:
GET https://rickandmortyapi.com/api/character/?name=morty&status=alive
The server responds with the following data:
{
"id": 27,
"name": "Artist Morty",
"status": "Alive",
"species": "Human",
"type": "",
"gender": "Male",
"origin": {
"name": "unknown",
"url": ""
},
"location": {
"name": "Citadel of Ricks",
"url": "https://rickandmortyapi.com/api/location/3"
},
"image": "https://rickandmortyapi.com/api/character/avatar/27.jpeg",
"episode": [
"https://rickandmortyapi.com/api/episode/10",
"https://rickandmortyapi.com/api/episode/28"
],
"url": "https://rickandmortyapi.com/api/character/27",
"created": "2017-11-05T08:59:07.457Z"
}
REST API Testing:
One of the best ways to test REST API is by using the Postman application.This tool is extremely helpful as you can structure the HTTP requests and try out various HTTP methods.
What are the Main Advantages of using REST APIs?
Some of the benefits to note while creating a REST API are:
What are the main Disadvantages of using REST APIs?
Not everything is perfect, there are also some downsides to using REST APIs, some of them are:
Developed internally by Facebook in 2012 before publicly releasing it in 2015, GraphQL is an open-source query language that is often touted as an alternative to REST API. Just like REST API, GraphQL is an architectural style for delivering data using HTTP method. GraphQL was designed to address the ongoing problems of REST API such as data-fetching and multiple endpoints. A common misconception with GraphQL is that it is a database technology however that isn’t the case. Just like REST, GraphQL is used to either retrieve or modify the data.
GraphQL revolves around these major components: queries, mutations, resolvers and schema.
Here's a GraphQL Example for to help us visualize it:
Being a query language, GraphQL tailors requests following the requirements of a client and responds in a JSON format only when the requirements are fulfilled.
e.g- Considering the same scenario in REST case, GraphQL makes a single query to the server to fetch the name and status of a character:
query {
characters(filter: { name: "rick" }) {
results {
name
status
}
}
}
The JSON response
{
"data": {
"characters": {
"results": [
{
"name": "Rick Sanchez",
"status": "Alive"
},
{
"name": "Adjudicator Rick",
"status": "Dead"
},
{
"name": "Alien Rick",
"status": "unknown"
},
{
"name": "Antenna Rick",
"status": "unknown"
},
{
"name": "Aqua Rick",
"status": "unknown"
},
{
"name": "Black Rick",
"status": "Alive"
},
{
"name": "Bootleg Portal Chemist Rick",
"status": "Dead"
},
{
"name": "Commander Rick",
"status": "Dead"
},
{
"name": "Cool Rick",
"status": "Alive"
},
{
"name": "Cop Rick",
"status": "Alive"
}
]
}
}
}
Let's now have a look at how Testing looks in GraphQL:
The GraphiQL or GraphQL Playground is extremely useful when running your queries and mutations to inspect/test your API.
Another option for testing the GraphQL API is using Postman as it has an inbuilt support to run GraphQL queries. Postman supports working with GraphQL by:
query {
event(id: "5879ad8f6672e70036d58ba5") {
title
address
host {
firstName
}
timeSlots {
totalCount
nodes {
startAt
}
}
}
location(place: "Los Angeles") {
city
weather {
summary
temperature
}
}
}
and response:
{
"data": {
"event": {
"title": "End of Unix Time",
"address": "Los Angeles, CA, USA",
"host": {
"firstName": "Joshua"
},
"timeSlots": {
"totalCount": 2,
"nodes": [
{
"startAt": "2018-08-31T12:00:00"
},
{
"startAt": "2038-01-18T21:00:00"
}
]
}
}
},
"location": {
"city": "Los Angeles",
"weather": {
"summary": "Cloudy with periods of rain",
"temperature": 77
}
}
}
{
__schema {
types {
name
description
}
}
}
and response:
{
"data": {
"__schema": {
"types": [
{
"name": "String",
"description": "The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text."
},
{
"name": "__Schema",
"description": "A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations."
}
]
}
}
}
The core differences between REST and GraphQL are:
REST | vs GRAPHQL |
---|---|
A server-driven architecture. | A client-driven architecture. |
Need to make multiple API calls. | Prevents multiple API calls unlike REST. |
Has no concept of schema/type system. | GraphQL is strongly typed which means that it helps in defining what an API looks like. |
Fetching little or more than the required data which could lead to over-fetching or under-fetching. | Solves the problem of over-fetching. |
Weak performance in mobile applications. | Built to address the performance issues of a mobile application. |
Has an in-built cache support. | Does not have an in-built caching support system. |
Suitable for small applications with consistent data. REST usually focuses on standard client to server communication. | Ideally used by companies when dealing with complex, cross- platform applications and rapidly changing data. |
Handles multiple HTTP status codes to communicate with the client. | Returns a 200 status code irrespective of the success of the query. |
Can support multiple data formats. | Returns the data in JSON format. |
Hard to maintain consistency across platforms. | Consistent across a variety of platforms. |
REST uses various HTTP methods such as GET, POST, PUT, PATCH, etc for either retrieving or modifying the data. | Usually the GraphQL queries are performed using the HTTP POST request method. |
One query can handle only one router function each time. | Single query can call various resolvers to fetch data from multiple resources. |
A widely accepted standard with a mature ecosystem. | Seen as a revolutionary alternative to REST however it is not implemented that often. |
Gets challenging to maintain different versions of a REST API. | Need not worry about maintaining old versions of API as GraphQL has @deprecated annotation that lets the client know which field can no longer be used while also maintaining. |
When choosing between GraphQL vs REST, we need to consider certain aspects such as the skill set of developers, the number of data sources and changes in the data sources. Ideally, if you’re dealing with a lot of data sources, GraphQL would be a better choice as you can abstract data sources at the backend and invoke the requested data. Similarly, if you’re dealing with frequent changes in the data source, GraphQL is suitable as you can swap the resolvers easily.
According to a study founded by ProgrammableWeb in 2017, roughly 80% of APIs were designed in REST style. REST is suitable in scenarios where developers with a tight schedule are comfortable in designing the API according to REST constraints. Also who controls the client is equally important since GraphQL is client-centric and not being able to control the client would make it difficult to deploy a graphql client.
Deciding which API technology is better than the other is not an easy task as REST and GraphQL both have their pros and cons. GraphQL was primarily created to deal with the shortages of REST API such as avoiding multiple round trips and offering better bandwidth due to the shift in mobile applications. However, GraphQL fails to deal with issues related to monitoring and error reporting. In this case, REST has the upper-hand as it returns HTTP status codes according to the error.
Choosing an API design architecture ultimately boils down to the requirements of the business. It wouldn’t be wise to assume that a particular architectural style fulfills every application's requirements. To get the best of both worlds, a combination of REST and GraphQL can be useful in dealing with different scenarios.