REST API Vs GraphQL: Fetch What You Want!

@pramodchandrayan
SysopsMicro
Published in
8 min readSep 15, 2020

What is GraphQL? Why You Should Care About GraphQL?

What Is GraphQL?

GraphQL is a kind of Query syntax that defines the way any server-side data needs to be fetched using API’s

GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.

GraphQL has three main characteristics:

  • It lets the client describe exactly what kind of data it is interested in.
  • One can source data from multiple data sources.
  • It uses a type system to describe data.

Practically speaking, the GraphQL layer lives between the client and one or more data sources, receiving client requests, and fetching the necessary data according to your instructions.

How Does It Work?

In Order to understand as a layman, how does GraphQL works at a higher level, we need to first understand REST API’s

What Is REST?

REST is an acronym for REpresentational State Transfer. It is an architectural style for distributed hypermedia systems and was first presented by Roy Fielding in 2000

Let’s take a use case:

  • You are hungry and you want to east pizza, but also you want to have your favorite tomato ketchup, to spice p your taste buds. Also, you want to have an energy drink to complement your appetite. Now these three items are supposed to be sourced from three different sources which in this case is
  • Dominos Pizza
  • Karana store for ketchup
  • And Fragrance For Room to create an ambiance worth enjoying

So if REST API has to be used :

As these three items are to be sourced from three different sources, In Rest we will have to make three different REST API calls

Fig 1.0

GraphQL: Single End Point, Single API call is required:

In GraphQL, you just need to make one API call with a single endpoint, called GraphQL. Here the GraphQL endpoint is like your Google assistant, to whom you have passed the location and items info with the single API call, rest is taken care by that assistant to help you serve your appetite needs,

Fig 2.0

This personal assistant has its own structured language to talk to all the server resources which we call A Query language.

Why GraphQL?

  • With GraphQL, you can be very specific to your need.

You Ask & You Get What You Really Need

  • With It, you always get the predictable results
  • Sigle endpoint is all you need to source multiple resources.

As per the official graphQL site:

While typical REST APIs require loading from multiple URLs, GraphQL APIs get all the data your app needs in a single request. Apps using GraphQL can be quick even on slow mobile network connections.

  • Frontend apps, using GraphQL are fast and stable because they control the data they get, not the server.
  • Unlike REST API, where you ave multiple operation types, GET, POST, DELETE, PATCH, in GraphQL you just need a POST method which queries only a single endpoint.
  • In GraphQL One can make changes to the existing API to help it evolve without versioning.
  • Unlike REST, by allowing you to define a schema, GraphQL gives you a lot of benefits, like automatic validation and introspection.

One can add new fields and types to their GraphQL API without impacting many of their existing queries. Aging fields can be deprecated and hidden from tools. By using a single evolving version

As per graphql website:

GraphQL APIs give apps continuous access to new features and encourage cleaner, more maintainable server code.

What Are The Key Components Of GraphQL?

Here are some of the key the Server Side Components, where GraphQL exists as an endpoint.

  • Queries
  • Schemas and Types
  • resolver

Queries:

The request one makes to the GraphQL endpoint happens in the form of the query structure.

A GraphQL query is a request coming from the application to fetch data from database or legacy APIs.

For the example, in Fig2.0 the query will look like

query {  graphql {    pizza    saltednuts    Fragrance  }}

So a query in GraphQL comprises documents and underlying operations like mutation, a subscription that is understood well by a GraphQL execution engine.

Schema:

For any GraphQL server-side implementation, Scheme plays a crucial role in describing the functionality available for front-end clients that connect to it.

The most basic components of a GraphQL schema are object types, which just represent a kind of object you can fetch from your service, and what fields it has.

In the GraphQL schema language, we can represent them as shown below

Example :

type Query {
welcome:String
students:[Student]
}

type Student {
id:ID!
firstName:String
lastName:String
class:String
enrollId:String
}

The root of the schema here is the Query type. The query has two fields − welcome string and Student array that returns String and a list of students respectively. Students here GraphQL Object type since it contains multiple fields. The ID field is declared as non-nullable.

Resolver:

Your GraphQL endpoint has to be told, where to find the requested data or fetch the data from. Resolver facilitates this knowhow to the GraphQL endpoint. Resolver comprises of the method responsible to generate a response for a GraphQL query. Every resolver method in a GraphQL schema looks like

A resolver tells GraphQL how and where to retrieve the data w.r.t to a given field.

fieldName:(root, args, context, info) => { result }

The key concept to understand here is that with GraphQL, your API schema and your database schemas are decoupled.

One can write a custom code within the resolver method, which can also help us to make any desired modification of the database content. This kind of process executed by any resolver is known to be they’re known as mutation resolvers.

REST API Vs GraphQL :

Before we dig deeper into comparing these two API paradigms, let’s see what are some of the commonality between these two :

Similarity :

  • They both are the standard specifications to develop and consumer API’s
  • They both use Http, protocol.
  • Both Exchanges the JSON data
  • Any server-side languages or any front-end framework works perfectly with both. Like you can use node, PHP, Python, Springboot, etc to write your web services and this service can be consumed by any front-end mobile application or web application irrespective of which language or framework that application is built with.
  • REST & GraphQL both supports statelessness.

Differences Between GraphQL & REST API:

  • GraphQL only supports the POST method while REST support GET, POST, DELETE, PATCH, etc.
  • Unlike REST, GraphQL returns result only in JSON representation
  • In the case of data retrieval from the server: Unlike GraphQL, REST API can end up making requests to multiple endpoints, whereas, GraphQL, only has a single endpoint with which one has to access at the time data fetching on a server.

For Example :

In REST:

  • /students/:id, can be one api format to fetch a student
    - /student/:id/siblings, can be another API endpoint to fetch the siblings of the given student

But in GraphQL :

You just need to make a single call to the single GraphQL endpoint, which will be like /graphql with the following query:

{
student {
name: string
siblings {
name: string
class: string
}
}
}
  • The case of an extra parameter: Over & Under Data Retrieval

While using REST API, if the schema is not well planned or due to unavoidable context, you may end up fetching the parameters in the response which may even be not required at the client-side interface. But this can be easily handled with GraphQL It gives you the power to get the desired result by being selective at the time of asking from the server.

Having said that it is important to notice that :

If one is pretty clear of what is the client-side requirement, one can with the use of HTTP2 can design REST API in such a way that there will be little to no over-fetching and zero impact on the performance.

  • Server-Side Caching: The Case Of State Management

In graphQL server and client, the app is generally coupled, when client-side coding is being done, the state of the application is not controlled by the server. Unlike REST, GraphQL has no caching mechanism in place, hence leaving the clients with the responsibility of taking care of caching on their front-end.

Cons Of GraphQL: IS GraphQL The Clear Winner?

Is everything Rossy about GraphQL, no not at all, it would be an extreme exaggeration if one claimes that. It is imperative to understand that it boils down to the use case of the developer or an organization. if they are looking for a backend system where they require a structured and disciplined approach and if the API developer has mastered this skill-set to support it, REST can always do what GraphQL do.

If the application is very complex and any interface of the application requires loads of data to be fetched at one go, to avoid many network calls, GraphQL can be the way out, but if one simply wants to separate the data retrieval concern they can break the same into multiple API’s Using REST and can have better control over what they need if making multiple API call is not an issue for them.

So here the question of which one is better than the other is not very relevant, just finalize what you want? How much you want? What is the tradeoff between speed, consistency, and discipline? And then architect your system requirements accordingly.

GraphQL has it’s own limitations and constraints

  • Not suitable if one needs to handle the response in the format other than JSON
  • Not very well suited to tackle the issues of the distributed system
  • When it comes to scalable architecture like microservices, the REST Paradigm is pretty well suited, GraphQL may struggle here.
  • Error Handling: Unlike REST Error handling is not very intuitive and straightforward. Depending on the HTTP status code like 404, 503, 500, we can easily tell what are those errors signifying, while in GraphQL, when operated over HTTP, we will always get a 200 OK response status. When an error occurs while processing GraphQL queries, the complete error message is sent to the client with the response.
  • In a simple application, GraphQL is not very intuitive to use. It complicates the stuff due to the requirement to handle - Types, Queries, Mutators Resolvers, High-order components. which may not be easy to manage when it comes to maintainability
  • It’s easier to use cache management at web side with REST as compared to GraphQL

Who all are using GraphQL?

As per graphql site :

Almost more than 90 big to mid-level companies are already taking the benefit of GraphQL

  • Airbnb
  • Facebook
  • Intuit
  • Coursera
  • Shopify
  • twitter
  • Starbucks
  • Rakuten

are some of the big-name who has been an early adopter of GraphQL

Please visit on GraphQL to know more :

What’s Next?

Hands-on use case of GrpahQL and transforming REST API into GraphQL structure. We will also do some performance benchmarking in the series of Web services.

Till then, stay tuned and keep learning. Anyone looking to contribute there, please reach out and I will be happy to add you as a writer on Life Learning publication, which I have just started to help learners out there

Thanks a lot…..

--

--

@pramodchandrayan
SysopsMicro

Building @krishaq: an Agritech startup committed to revive farming, farmers and our ecology | Writes often about agriculture, climate change & technology