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
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 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:
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
}
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.
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!
Please follow, like and share this article. It will help us lot. Thank you.