DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Bentil Shadrack for Documatic

Posted on

REST API vs GraphQL

You have probably heard about GraphQL, but you might not be entirely sure how and whether it differs from REST. You're in luck, then! Today, we'll go over some fundamentals regarding both REST and GraphQL and the various use cases of each of them.
The popularity of GraphQL as a replacement for REST APIs is growing. Though it isn't necessarily a "replacement".
You will need to decide between GraphQL, REST API, or a combination of both depending on your use cases. Let's compare REST with GraphQL and learn some of the benefits of GraphQL in order to make a more informed conclusion.

REST APIs

rest api

A REST (Representational state transfer) API is an architectural style for an application program interface (API) that uses HTTP requests to access and use data. That data can be used to GET, PUT, POST and DELETE data types, which refers to the reading, updating, creating and deleting of operations concerning resources.
A RESTful API uses HTTP methods to carry out CRUD (Create, Read, Update, and Delete) processes while working with data.
In order to facilitate caching, AB testing, authentication, and other processes, headers offer information to clients and servers.
The body houses data that a client wants to transmit to a server, like the request's payload.

GraphQL APIs

graphql apis
GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. 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. With popular known organizations like Twitter, Expedia, Shopify, to mention a few, GraphQL has been widely adopted and is primarily maintained and developed by the GraphQL Foundation.

GraphQL vs. REST:

diff
The key difference between GraphQL and REST APIs is that GraphQL is a query language, while REST is an architectural concept for network-based software.
Again, The way that data is supplied to the client is where GraphQL and REST diverge the most. In a REST design, a client submits an HTTP request, and data is returned as an HTTP response. In a GraphQL architecture, a client submits queries to obtain data.

Typical Scenarios

REST APIs

Let's say you have an API to fetch a student data. In a typical REST scenario, this is what the request/response would look like:

// HTTP REQUEST
GET api/students/1 || api/students?id=1

// HTTP RESPONSE
{
   "id": 1
  "name": "john doe",
   "class": 3,
   "age": 11
}
Enter fullscreen mode Exit fullscreen mode

In the example above, the response to the request sent to the server will be an object of all data about the student with id 1.
This can sometimes take a longer time depending on the size of the data due to the over-fetching nature of REST

GraphQL

In GraphQL, data if fetched by strictly listing the number of fields needed. This restricts fetching all data at a time. Consider the GIF below for fetching user data using graphQL.

gif1

Things to consider when choosing between GraphQL and REST

Security

REST API makes use of HTTP, allows encryption using Transfer Layer Security, and provides a variety of API authentication options. TLS makes assurance that data transfer between two systems is private and unaltered. Web tokens that support JavaScript Object Notation (JSON) finish the HTTP authentication process for secure data transfer from web browsers.

GraphQL's security controls are not as developed as those in the REST API. In order to make use of current features like data validation in GraphQL, developers must devise new authentication and authorization techniques.

Usability

The REST API makes use of URI and HTTP techniques, which make it challenging for the API to anticipate what will happen when contacting a new endpoint. The lack of specified versioning requirements in REST allows providers to take their own method.

With GraphQL, you can send a request to your API and receive the precise response without the need for further additions. As a result, extremely predictable responses from GraphQL queries offer good usability. GraphQL adopts a straightforward methodology and does not version APIs.

Performance

Developers can get data with GraphQL with just one API request. In order to avoid under- and over-fetching of data, the flexible style defines the structure of information requests and returns the same structure from the server.

REST APIs, in contrast to GraphQL, have rigid data structures that may first return irrelevant information (over-fetching). As requests take time to reach the proper data and deliver pertinent information, developers must make several calls.

Caching

All GET endpoints for REST APIs can be cached on the server or through a CDN. They can also be stored by the client for regular use and cached by the browser. GraphQL is supplied through a single endpoint, typically (/graphql), and deviates from the HTTP spec. As a result, the queries cannot be cached the same way REST APIs can.

However, because of the available tools, caching on the client side is superior to REST. The schema and type system of GraphQL are used by some of the clients employing caching layers (Apollo Client, URQL), allowing them to keep a cache on the client side.

Error Handling

Every GraphQL request, success or error returns a 200 status code. This is a visible difference compared to REST APIs where each
status code points to a certain type of response.

Status Code REST GraphQL
200 Ok Ok
400 Bad Request -
401 Unauthorized -

Errors with REST APIs can have any code other than 200, and the client handling the error should be aware of all possible codes.

Any legitimate answer in GraphQL should be 200, including data and error responses. The client side tooling will assist in managing errors more effectively. Errors are handled as part of the response body under a particular errors object.

Conclusion

Lets take a recap of what we've discussed above.

REST GraphQL
An architectural style largely viewed as a conventional standard for designing APIs A query language for solving common problems when integrating APIs
Simplifying work with multiple endpoints requires expensive custom middleware Allows for schema stitching and remote data fetching
Doesn't offer type-safety or auto-generated documentation Offers type-safety and auto-generated documentation
Response output usually in XML, JSON, and YAML Response output in JSON
Supports multiple API versions No API versioning required
Uses caching automatically Lacks in-built caching mechanism
Deployed over a set of URLs where each of them exposes a single resource Deployed over HTTP using a single endpoint that provides the full capabilities of the exposed service
Uses a server-driven architecture Uses a client-driven architecture

With the curefully curated differences above, I hope you will be able to choose which of the technologies to use depending on your use case.

Happy Hacking!

Happy Hacking

Please follow, like and share this article. It will help us lot. Thank you.

Top comments (18)

Collapse
 
brense profile image
Rense Bakker • Edited on

Its worth noting that graphql lives on top of the HTTP protocol as well (its nothing more than a post request) and therefore it benefits from all the security benefits that come with it including https, the ability to send authorization headers, etc. Also graphql servers can return status codes other than 200. For example if you use Apollo server, it will return a status code of 400 if your graphql query is malformed.

Collapse
 
qbentil profile image
Bentil Shadrack

Wow!
Thank you for this inputπŸ‘

Collapse
 
jefflindholm profile image
Jeff Lindholm

Wrong on so many levels. REST is not an RPC protocol, which is what you described, admittedly that is what most people call REST but that is not what the original specification says.
Look into HATEOS that is more what the original was supposed to be, but even the RPC is not just CRUD operations. Which is all GraphQL is.
REST payloads should include things like where to get the next values if it is a list type request, it should show how to get details if it is a summary dataset, it should also have a reference link to get the same answer again, or refresh it if the data could be changing.
GraphQL is nice and pretty cool, but it is also pretty hard to write all the connections for a complicated dataset, and it is not free.
It was also done in more of an RPC approach before in the OData specification which could do the same things, excluding fields, etc. But again both of these have to be written to best take advantage of this, most GraphQL services I have seen, still get everything from the database/storage and then limit the payload, which is an optimization, but might not actually be the place where the most time would have been saved.

Collapse
 
bklau2006 profile image
BK Lau • Edited on

GraphQL is essentially a smart "aggregator" playing the role of data orchestrator( See dev.to/jacobsee/microservice-coord...)
The main difference from REST comes to 2 essential mechanisms:

1) Parsing and validation of request "shape" via schema parsing

2) Forwarding request fragments to different endpoints(microservices/data providers) and collect and aggregate the various data into the "shape" requested in #1

As result, technically-speak, GraphQL should be able to use other protocols besides HTTP protocol. Though current spec or implementation mainly uses HTTP.

Collapse
 
missamarakay profile image
Amara Graham

YES! Thank you for this great post!

Though it isn't necessarily a "replacement".
You will need to decide between GraphQL, REST API, or a combination of both depending on your use cases.

I really liked seeing this specifically called out.

Collapse
 
qbentil profile image
Bentil Shadrack

You are most welcome.
I’m glad you like it!

Collapse
 
andrewbaisden profile image
Andrew Baisden

Fantastic comparison I know so many people who keep asking what the difference between the two is and why they should even learn GraphQL.

Collapse
 
qbentil profile image
Bentil Shadrack

Thank you Andrew😊

Collapse
 
fruntend profile image
fruntend

Π‘ongratulations πŸ₯³! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up πŸ‘

Collapse
 
qbentil profile image
Bentil Shadrack

AwesomeπŸŽ‰πŸŽ‰πŸŽ‰πŸ™Œ

Collapse
 
professorhaseeb profile image
Haseeb ur Rehman

Nice article.

Also check 'restql' to does the same for rest apis on python,
useful for anyone who dont want to upgrade to graphql instantly but want to enjoy this structure.

Collapse
 
qbentil profile image
Bentil Shadrack

That's awesome!
I will check it out asap

Thank you Haseeb

Collapse
 
konaduakwasiakuoko profile image
Konadu Akwasi Akuoko

Thanks a lot for this Shadrack

Collapse
 
qbentil profile image
Bentil Shadrack

You are welcome Akwasi

Collapse
 
yukikimoto profile image
Yuki Kimoto - SPVM - Perl Club

Thanks.

Collapse
 
pterpmnta profile image
Pedro Pimienta M.

Excelent post.

Collapse
 
qbentil profile image
Bentil Shadrack

Thank you Pedro!

Collapse
 
lovepreetsingh profile image
Lovepreet Singh • Edited on

πŸ”₯ Very Helpful. Kindly checkout my blog at dev.to/lovepreetsingh/make-thousan...

Tired of sifting through your feed?

Find the content you want to see.

Change your feed algorithm by adjusting your experience level and give weights to the tags you follow.