GraphQL vs Rest: which one is better

GraphQL vs Rest: which one is better
Techiio-author
Written by Debarghya DasDecember 1, 2021
20 min read
GraphQL
0 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 0 VIEWS SHARE
Techiio-author
Debarghya Das

Junior Front-End Developer

The goal is to provide a brief explanation to anyone who still has not got to know GraphQL, clarify exactly what it does better than REST.

About GraphQL

GraphQL is a query language for APIs that enables declarative data fetching in order to give the client the power to specify exactly the data that is needed from the API. It makes easier to evolve APIs over time.

Now that we know what GraphQL is, I want to clarify what it is not, as I feel that there is still some confusion about it.

Firstly, it does not have anything to do with databases. It is not an alternative to SQL or a brand new ORM.

Secondly, it is not a REST replacement, but an alternative. You don't have to pick between one and the other, they can happily co-exist in the same project.

Last but not least, GraphQL is not complicated or scary. It is quite easy to understand its declarative nature and exactly how it is possible to take the best from it.

blogpost

Who created GraphQL

GraphQL was developed internally by Facebook in 2012 before being open-sourced in 2015, with its stable version released just in June 2018. On 7 November 2018, the GraphQL project was moved from Facebook to the newly-established GraphQL Foundation, hosted by the non-profit Linux Foundation.

Lee Byron, GraphQL's creator, aims to make GraphQL omnipresent across web platforms.

Which companies use GraphQL

GraphQL is being used by teams off all sizes, in many different environments and languages. The main companies that are using GraphQL are Facebook, Github, Pinterest and Shopify.

About Rest

REST was defined by Roy Fielding, a computer scientist that presented the REST principles in his PhD dissertation in 2000.

REST (Representational State Transfer) is a software architectural style that defines a set of constraints which make any web service – a true RESTful API.

blogpost

The REST constraints are:

Client-server architecture

Client-server architecture means that the user-interface concerns should be separated from the data storage concerns to improve the user interfaces portability across multiple platforms.

blogpost

Stateless

A stateless server does not persist any information about the user who uses the API. This means that the server does not remember if the user is sending is first request or not.

blogpost

Cacheability

REST API responses must define themselves as cachable or non-cachable to prevent clients from providing any inappropriate data that can be used on future requests.

Layered system

A Layered system means that if a proxy or load balancer is placed between client and server, the connections between them should not be affected, and the client did not know if is connected to the end server or not.

Uniform interface

A Uniform interface suggests that it should be a uniform way of interacting with a given server despite the device or application type (website, mobile app). The main guideline is that each resource has to be identified on requests.

Why was GraphQL created if there's already REST

There are two main reasons why companies such as Facebook, Netflix and Coursera started developing alternatives to REST:

  1. In the early 2010s, there was a boom in mobile usage, which led to some issues with low-powered devices and sloppy networks. REST isn't optimal to deal with those problems;
  2. As mobile usage increased, so did the number of various front-end frameworks and platforms that run customer applications. Given REST's firmness, it was harder to develop a single API that could fit the prerequisites of each customer.

If we go even further, we realize that the main reason why an alternative solution was identified was because most of the
data used in modern web and mobile applications has a graph shape. For instance, news pieces have comments, and
those comments may have features such as likes or spam flags, which are created or reported by users. This example
describes how a graph looks like.

Consequently, Facebook started developing GraphQL. At the same time, Netflix and Coursera were also working on
alternatives themselves. After Facebook open-sourced GraphQL, Coursera dropped their efforts and adopted the new
tech. Netflix, however, continued developing their own REST alternative and later open sourced Falcor.

Why GraphQL is better than REST

In this section I will go point by point through a practical example, comparing REST to GraphQL in order to demonstrate the flexibility of Facebook's query language.

Imagine that you have a blog, and you want the front page to show all the latest posts. In order to achieve this, you need to fetch the posts, so you will probably do something like this:

GET /api/posts
[
  {
    "title": "Cooler post",
    "subtitle": "...",
    "date": "07/05/2019"
  },
  {
    "title": "Cool post",
    "subtitle": "...",
    "date": "06/05/2019"
  }
]

But what if you want to see the author as well? You have three options to achieve this:

  • Fetch the authors from another resource:
GET /api/post/:id
{
  "post": {
    ...,
    "author": {
      "name": "Dio Brando"
    }
  }
}
  • Modify the resource to also return the author:
GET /api/posts
[
  {
    ...,
    "author": {
      "name": "Dio Brando"
    }
  },
  {
    ...,
    "author": {
      "name": "Johnathan Joestar"
    }
  }
]
  • Create a new resource that returns the posts with the author:V
GET /api/postsWithAuthor
[
  {
    ...,
    "author": {
      "name": "Dio Brando"
    }
  },
  {
    ...,
    "author": {
      "name": "Johnathan Joestar"
    }
  }
]

Each of these approaches will create a problem of its own, so let's have a look at them one by one to see how GraphQL is able to solve the following problems.

Under-fetching

With the principal approach – bringing the creators from another asset – you will wind up with two server demands rather than one, and as you keep on scaling, you might have considerably more demands to various endpoints to bring every one of the required information.

With GraphQL, this would not happen. You would only have one request, and you would not have to make multiple round trips to the server, as seen below:

query {
  posts {
    title
    subtitle
    date
    author {
      name
    }
  }
}

Over-fetching

Looking at the second approach – modifying the resource to also return the author – you can see that it solved the problem pretty nicely. However, changing a resource may have a secondary effect elsewhere on your application. More precisely, over-fetching.

Let's go back to your blog, but this time you also have a sidebar showing off the top monthly posts with their titles, subtitles and date, that is using the resource /api/posts. Since you modified the resource, now it also shows the author with it. However, we don't need it for the sidebar.

While this may not look like a problem, for users on limited data plans, having a website fetch useless data is not ideal. Since GraphQL allows the client to only fetch the needed data, this problem would not exist:

query {
  posts {
    title
    subtitle
    date
  }
}

Slow front-end development

Finally, we should examine the last methodology – making another resource that profits the posts with the creator – since it is a not unexpected example to structure the endpoints as indicated by the perspectives in your task.

While this may solve problems such as the one described above, it also slows down the front-end development, since each specific view needs its specific endpoint. If at any point a view needs new data, the development has to slow down until the endpoint is updated.

Again, since GraphQL gives power to the client to fetch the needed data only, nothing slows down, as it's very simple to just add a new field to a query.

You would get from this:

query {
  posts {
    title
    subtitle
    date
  }
}

To this:

query {
  posts {
    title
    subtitle
    date
    author {
      name
    }
  }
}

GraphQL vs REST comparison

Differences

Let's just do a quick recap regarding the differences between REST and GraphQL:

  • GraphQL is a query language and a set of tools that use HTTP to work on single endpoints in order to optimize flexibility and performance.
  • In GraphQL, data is organized into a graph, and objects are structured by nodes following a schema.
  • RREST is an architectural concept for network-based software that has typically been used to develop new APIs.
  • GraphQL solves both over-fetching and under-fetching issues by allowing the client to request only the needed data;
  • Since the client now has more freedom in the fetched data, development is much faster with GraphQL than what it would be with REST.
  • In GraphQL, the identity of an object is separated from how a developer fetches it. In REST, the endpoint is the identity of an object.
  • In GraphQL, the server determines the available resources by allowing the client to request the needed data at a specific time. In REST, the resources' size is defined by the server.
  • In GraphQL, a single query can call various resolvers to provide a response with multiple resources. In REST, one query usually calls one route handler function.
  • Since GraphQL follows the relationships defined in the schema, it is possible to transverse from the entry point to the related data with a single request. Contrarily, REST requires calling several endpoints to fetch related resources.

Similarities

As previously mentioned, GraphQL does not replace REST. Despite their differences, GraphQL and REST also have similarities:

  • They can both be fetched by an HTTP GETrequest with a URL and return the request in JSON data.
  • GraphQL and REST allow the specification of IDs for resources.
  • Both GraphQL (fields) and REST (endpoints) call functions on the server.
  • They both have entry points into the data. In GraphQL API, the list of fields (considering both the Mutationand the Query types) is identical to the list of endpoints in a REST API.
  • GraphQL and REST are able to distinguish when an API is intended to write or to read data.

Wrap up

GraphQL provides a smooth and fast development environment with its declarative and flexible nature, offering many improvements over REST.

It already has a large community and a vibrant ecosystem, and was already implemented in several popular languages, such as JavaScript, Go and Java.

While this post just plunged the toes into the sea that is GraphQL, its site has a plenty of data and is an astounding spot to learn and begin utilizing GraphQL.

On the off chance that you are expecting to foster an API to be utilized on a versatile application you ought to have GraphQL as first choice since transfer speed utilization matters. Assuming your application requires a hearty API, with reserving and an observing framework you ought to go with REST.

With a lot of being said, it's anything but an ideal innovation, it actually has several downsides when contrasted and REST. Yet, taking into account how youthful it is, the future searches amazingly brilliant for GraphQL.

GraphQLvsRest
GraphQL
Rest
0 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 0 VIEWS SHARE
Was this blog helpful?
techiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plan
You must be Logged in to comment
Code Block
Techiio-author
Debarghya Das
Junior Front-End Developer
Techiio-followerTechiio-followerTechiio-followerTechiio-followerTechiio-follower
+3 more
74 Blog Posts
227 Discussion Threads
Trending Technologies
15
Software40
DevOps46
Frontend Development24
Backend Development20
Server Administration17
Linux Administration26
Data Center24
Sentry24
Terraform23
Ansible83
Docker70
Penetration Testing16
Kubernetes21
NGINX20
JenkinsX17
Techiio-logo

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Developed and maintained by Wikiance
Developed and maintained by Wikiance