DEV Community

Cover image for GraphQL vs REST
Ujwal Kumar
Ujwal Kumar

Posted on

GraphQL vs REST

Introduction to GraphQL vs REST

REST is one of the most common way of developing API(also known as Application Programming Interface). People have been using REST for a long time but since GraphQL became open source in 2015, there have been constant debates on whether GraphQL is superior to REST API.

As everything, REST API and GraphQL both have pros and cons, which need to be considered while designing your solutions. In this article I would like to explain what is REST API and what is GraphQL. I will go through the major difference between them and try to explain the pros and cons of both them so people can make a good choice based on their requirements.

What is REST API?

REST API was presented in 2000 by Roy Fielding. REST stands for Representational State Transfer. REST is a set of architectural constraints, not a protocol or a standard. API developers can develop REST in different ways. When a request is made via a REST API, it transfers a representation of the state of the resource to the requestor. This information can be delivered in one of the several formats: JSON (Javascript Object Notation), HTML, XML or even plain text. JSON is the most popular file format to use because it's language-independent as well as readable by both humans and machines. REST API communicates using HTTP requests with GET, POST, PUT, PATCH and DELETE methods

Image description

In the above image you can see that client is sending the request using one of the REST API methods, next server responds with XML, HTML or JSON data depending on the request.

There are certain constraints that should be followed be while designing a REST API.

1. Uniform Interface - It states that there should be a uniform way of interacting with the server irrespective of the client. There are four guideline principles of this constraint:

  • Resource Based - Individual resource are identified in a request.
  • Manipulation of Resources through Representation - Client has representation of resource and it should contain enough information to modify or delete the resource on the server.
  • Self-Descriptive Messages - Each message includes enough information to describe how to process the message.
  • Hypermedia as the engine of application state(HATEOAS) - The term hypermedia refers to any content that contains links to other forms of media such as images, movies, and text. REST API response can include links so that client can discover other resources easily by following the links.

2. Stateless - All communications between the client and the server needs to be stateless. The server does not store any information from the previous requests. Client needs to provide all the information in each request so that the server can process it as an individual request.

3. Cacheable - Every response should include whether the response is cacheable. Client will return the data from its cache for any subsequent request and there would be no need to send the request again to the server.

4. Client-server - This constraint means that client applications and server applications must be able to evolve separately without any dependency on each other.

5. Layered system - There can be lot of layers of intermediate servers between client and the end server. Intermediary servers may improve system availability by enabling load-balancing and by providing shared caches.

6. Code on demand - It is an optional feature. According to this, servers can also provide executable code to the client. The examples of code on demand may include the compiled components such as client-side scripts such as JavaScript.

REST request structure

Any REST request includes four essential parts: an HTTP method, an endpoint, headers and a body.

1. HTTP Method - An HTTP method describes what is to be done with a resource. Get, Post, Put, Patch and Delete are the common REST methods.

2. Endpoint - An endpoint contains a Uniform Resource Identifier (URI) indicating where and how to find the resource on the Internet.

3. Headers - These mainly store information relevant to both the client and server. Mainly, headers provide authentication data such as an auth token and the information about the response format.

4. Body - Body is used to convey additional information to the server. For instance, it may be a piece of data you want to send in a post request to be added on the server.

What is GraphQL?

GraphQL was developed by Facebook, which first began using it for mobile applications in 2012. The GraphQL specification was open sourced in 2015. GraphQL is a query language for APIs. GraphQL makes it possible to access many sources in a single request, reducing the number of network calls and bandwidth requirements.

Types and Resolvers in GraphQL

A GraphQL service is created by defining types and fields on those types, then providing functions(resolvers) for each field on each type. For example, a GraphQL service to fetch student details could have the type as below:

type Query {
  student(rollNo: String!): Student
}
type Student {
  name: String
  rollNo: String
}
Enter fullscreen mode Exit fullscreen mode

The resolver for the above query could be something like below

const resolvers = {
  Query: {
    student(parent, args, context, info) {
      return db.students.get(args.rollNo); // fetches student data from database based on rollNo
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Queries, Mutations, and Subscriptions in GraphQL

Queries, mutations and subscriptions form the core features of GraphQL and help us to leverage GraphQL to build better APIs.

Queries

Queries are data requests made by the client from the server. GraphQL only discloses single endpoint, allowing the client to determine what information it actually requires.

{
  Students {
    rollNo
  }
}
Enter fullscreen mode Exit fullscreen mode

The field ‘Students’ in the above mentioned query is known as the root field. This query will result in the rollNo of all the students.

{
  “Students”: [
    {“rollNo”: “A1”},
    {“rollNo”: “A2”},
    {“rollNo”: “A3”}
  ]
}
Enter fullscreen mode Exit fullscreen mode

Mutations

Mutations are used to create, update or delete data. The structure is almost similar to queries except for the fact that you need to include the word "mutation" in the beginning. For instance:

mutation {
  createStudent (name : “Daryl”, rollNo: ”A1”){
    name
    rollNo
  }
}
Enter fullscreen mode Exit fullscreen mode

Subscriptions

Subscriptions are a way to create and maintain real time connection to the server. Basically, a client subscribes to an event in the server, and whenever that event is called, the server will send the corresponding data to the client.

Let’s say we have an app where we need to fetch students in real time and want to subscribe to the event of creation of a new student. Below subscription could be used for this type of requirement:

subscription {
  newStudent {
    name
    rollNo
  }
}
Enter fullscreen mode Exit fullscreen mode

Comparison of GraphQL and REST

Usability

GraphQL allows you to send a request to your API to get the exact result without requiring anything extra from in the response. Thus, GraphQL queries return highly predictable results providing excellent usability.

With REST the behaviour of the API wildly varies depending on the URI and HTTP method chosen, making it difficult for consumers to know what to expect with a new endpoint.

Data Fetching

It is quite a common scenario to fetch more data than you need in REST than in GraphQL as each endpoint in REST specification includes a specific data format. Similarly, with REST it’s also common to under fetch the dataset, forcing clients to make additional requests to get relevant data. The case is quite different when it comes to GraphQL. Since it’s a query language and supports declarative data fetching, the users can only get what they actually need from the server.

Caching

Caching is an integral part of the HTTP specification that REST APIs can use. On the other hand, GraphQL has no caching system, thus leaving the users with implementing their own caching system.

Monitoring and Error Reporting

When using REST we can monitor the API usage based on status messages. On GraphQL you don't have that, because it always return 200 OK status response. A typical GraphQL error looks like this:

HTTP 200 OK
{
  errors: [
    {
      message: 'Something when wrong'
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Performance

Performance is one area where GraphQL has an advantage over REST. As mentioned in the data fetching section, due to the problem of under-fetching and over-fetching, REST API tends to perform poorly as compared to GraphQL

Security

REST provides several ways to enforce the security on your APIs. For instance, in methods like HTTP authentication, sensitive data is sent in HTTP headers, through JSON Web Tokens. GraphQL also provides some measures to ensure your APIs’ security, but they are not as mature as those of REST.

So which should I choose?

This really depends on your use case. Neither REST nor GraphQL are better than one another. They simply work differently.

If you are concerned about retrieving exactly the data you require and want a more declarative way to consume your API then probably GraphQL would be the better choice. Also it saves bandwidth by solving the problem of under-fetching and over-fetching.

REST provides an easier caching and monitoring system. REST has easier ways to implement authorisation and security in comparison to GraphQL. So if the above points are your primary concern, then go ahead with REST.

Top comments (0)