GraphQL vs. REST API: How GraphQL Outperforms the Traditional RESTful Approach
Over the years, Rest API has been the standard for creating production-grade APIs and is often a core part of software companies' products and business models. It was designed to outline how software like web apps and networks like the World Wide Web should function. It encourages using features we are accustomed to from the World Wide Web while rejecting the RPC-style approach to APIs.
However, REST had drawbacks like numerous network queries, and over-fetching data as REST API, clients have to mix and match multiple endpoints. GraphQL, created by Facebook, showed up in 2015 to address these issues with a new philosophy of customizing endpoints allowing you to have a single endpoint to query the data efficiently.
In this article, we'll compare REST API and GraphQL, looking at their strengths, and benefits, and finally conclude by choosing the best option for developing APIs in your next project.
What is an API?
API, short for Application Programming Interface, is a set of functions that enables applications to interact with external software components, operating systems, or microservices.
APIs enable different software applications to communicate with one another. They are classified into four types (public or open, partner, private, and composite) and have a variety of architectures, the most common of which is REST.
After the user requests an action, the application will send the data to an API, which will process the information and provide a solution to the user's request. The API will convert the returned data into something the user can understand.
Developers use APIs to make their jobs more efficient by reusing previously written code and only changing the relevant parts to the process they want to improve. Because the building blocks are in place, a good API makes it easier to create a program. APIs use defined protocols to allow developers to quickly and efficiently build, connect, and integrate applications.
Benefits of using APIs
Easier to add on new features -
Improve the User Experience - Information and services are more personalized thanks to an API. Customized content can be distributed to a new audience, and a tailored user experience can be made with the help of an API.
Improve developer flexibility and productivity
Security - APIs not only allow others to access an application's functionality and information, but they also control how and what other applications access.
What is a Rest API
REST, or Representational State Transfer, is an architectural style as well as a communications approach that is commonly used in web service development. REST-compliant systems, also known as RESTful systems, are distinguished by their statelessness and separation of client and server concerns.
There are five HTTP methods that are commonly used in a REST-based architecture: POST, GET, PUT, PATCH, and DELETE
. These are equivalent to the CRUD operations (create, read, update, and delete).
REST API deconstructs a transaction to create small modules. Each of these modules is now used to handle a specific aspect of the transaction. This approach provides more flexibility but takes a lot of time and effort to build from the ground up.
Statelessness
Requests sent from a client to a server will contain all of the necessary information for the server to understand the client's requests. This can be a part of the URL, query-string parameters, the body params, or even the headers. The URL uniquely identifies the resource, and the body contains the requesting resource's state. When the server processes the request, it sends a response to the client via the body, status, or headers.
HTTP Methods
The HTTP Protocol governs not only the methods permitted in a REST API, i.e., the action types that the client can request in a request, but also the status codes that the Server returns to maintain a smooth communication flow.
Four commonly used methods for a request-response between a client and server are: GET, POST, PUT and DELETE.
GET — This method asks for representations of the resource listed in the resource we are communicating with. A GET request doesn't alter the resource's state; it merely obtains data.
POST — This is the request method used in order to submit data to a resource, in essence creating a new resource. Using POST has the potential to actually cause a change in a resource's state and also can generate side effects on the server.
PUT — To replace current representations of the target resource with the request's data, this method is used. It may be thought of as a method that updates or edits something.
DELETE — As can be expected, this HTTP verb is used for deleting a specified resource.
A REST operation usually returns data from the server to the client; for instance, when in use, a GET request can be made on a URI that typically looks like /api/users
.
The REST response data then typically comes in property/value combinations and can be in formats like JSON, CSV, XML, or RSS:
{
"users": {
{
"id": "1",
"name": "Pat",
"age": "10"
},
{
"id": "2",
"name": "Sam",
"age": "15"
}
}
}
What is good about REST?
REST has its own set of benefits. The protocol includes instructions for optimizing performance. It is also a technology that is highly scalable. These features are available in GraphQL, but it is entirely up to the client to implement them.
REST-based interactions take place using constructs known to everyone who is used to utilizing the internet's HTTP protocol, which is a significant advantage of using REST from both a client and server standpoint. The use of standard HTTP status codes like the 404, 401, and 200
codes are used for all status communication in REST-based interaction.
Issues With REST APIs
Most of the limitations in REST APIs are usually in their architectural style and nature. REST-based applications must be stateless, and all state management duties must be handled by the client because HTTP, for example, does not save state-based data between request-response cycles.
Nature of multiple endpoints - Overfetching is the practice of a client downloading more data than the application actually needs.
REST is lightweight architecture
Over-fetching of information - Multiple requests are necessary with REST APIs in order to retrieve information, which has various unfavorable effects. Because the client cannot select the field or type of information to give, its algorithms lack specificity.
Isolated Layers - REST preserves separation at all web architectural tiers. A client's awareness of the server's communication is limited to essential communication layers. This signifies that the operation will proceed even if there is a load balancer or proxy.
What is GraphQL? - Why use GraphQL when there's already REST API
GraphQL is one of the most modern ways of building and querying APIs, allowing developers to request data in a much simpler way than ever before. GraphQL is a query language for querying data from any data source, whether an API or a database. GraphQL is an alternate option to build APIs in REST as it also allows users to fetch the required information in a single call rather than constructing several REST requests.
It is named Graph because the data is structured as a Graph Data Structure, as opposed to Linked List-style REST APIs. The key difference is that having "nodes," as in GraphQL, allows you to coalesce data from multiple "nodes," whereas conventional REST API is more linear in its data retrieval methods.
Image showing the simplicity of using a single GraphQL query over multiple GraphQL queries.
Let's say you have a book object, which contains a list of titles and pages, and comments denoted by an author. We are interested particularly in the comments of the book using name and text; we can do this:
query {
books(author:"George von Devto") {
title
pages
comments(rating:">=4") {
name
text
}
}
}
In the end, we go from one book (given by the book's author), get their comments (also provided by a book object), and fetch their names and texts in a single request. All of this is made possible by the way the data is structured.
Typically GraphQL consists of two elements:
GraphQL Server - A GraphQL server is a server-side GraphQL implementation. In other words, a GraphQL server exposes your data as a GraphQL API, which your client applications can use to query for information.
GraphQL Clients - GraphQL clients facilitate communication by abstracting away minor details and implementing extra features such as caching, query batching and deduplication, and static typing of GraphQL query results.
Strengths of GraphQL - Why you should consider GraphQL
Strongly typed: A specific type and a set of available fields are described for each level of a GraphQL query. This enables GraphQL to offer illustrative error warnings before running a query, much like SQL.
No Over-Fetching or Under-Fetching: Another significant advantage for GraphQL API clients is the ability to request specific data, even across related entities. This is especially important because different clients have different data requirements, either due to different business logic or simply because they present a different view of data (e.g., web vs. mobile), and may also have additional hardware limitations. In comparison, retrieving nontrivial data from a REST API is much more difficult.
Hierarchical: Another significant feature of GraphQL is its hierarchical structure. GraphQL naturally follows object relationships, whereas a RESTful service may require multiple round-trips (which can be resource-intensive on mobile networks) or a complex SQL join statement. This data hierarchy works well with graph-structured data stores and, ultimately, hierarchical user interfaces.
By making the responding server merely a single endpoint, GraphQL eliminates the issue of numerous round-trips. In essence, GraphQL extends the concept of a custom endpoint to the limit by turning the entire server into a single custom endpoint that can respond to all data queries.
Let's dive deeper into the differences with some examples.
How does REST differ from GraphQL - with Examples?
1. Prevent multiple API calls: In case you need more data, you can also avoid making numerous calls to your API. As in our example above, you don't need to make 2 API calls to fetch the title and pages separately. GraphQL eliminates the issue of multiple round-trips by making the responding server a single endpoint. GraphQL, in essence, pushes the concept of a custom endpoint to its logical conclusion by transforming the entire server into a single custom endpoint capable of responding to all data queries.
2. Amount of endpoints - There are several endpoints in the REST API, and we fetch resources by accessing various pathways for various data types. For instance, when we call the books resource at http://api.com/books
, we cannot call the same endpoint to retrieve all the comments on each book written by a particular author. To achieve that, we would have to call another endpoint at http://api.com/books/:id/comments
.
There is only one endpoint in GraphQL, which is usually http://api.com/graphql
. Queries or mutations are used to define requests. We can request multiple resources from the same endpoint by chaining the query.
3. Eliminates client's dependency on servers: With GraphQL, the client makes a request command which eliminates the need for the server to hardcode the shape or size of the data and decouples clients from servers. This implies that we can maintain and enhance clients independently of servers.
4. Insightful Analytics on the Backend - GraphQL provides fine-grained insights into the data requested on the backend. Because each client specifies precisely what information they want, it is possible to gain a thorough understanding of how the available data is used. This can aid in the evolution of an API by deprecating specific fields that are no longer requested by any clients.
5. Performance - In terms of GraphQL vs. REST performance, the inclination for Over-fetching and Under-fetching in RESTful services gives GraphQL a clear edge. You can probably end up collecting unnecessary data or be required to make many calls before acquiring the necessary data since REST APIs have inflexible data structures that are designed to return the specified data once they are triggered. These shortcomings can lengthen the time it takes for the server to return the requested data.
6. Schema Stitching - 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 associated resources.
query {
location: place("San Francisco"){
city
country
weather {
summary
Temperature
}
}
}
The capability of stitching schemas is a significant differentiator. To make multiple schemas accessible to the client, GraphQL can merge them into a single schema. For instance, combining the place API and weather API schemas by combining the information from several sources about a specific location's information.
Say we wish to retrieve a user's name. We have a REST API endpoint that we can use to send a GET request. The endpoint may be anything like /book/author/
. It will seem as follows if we use a curl request to place a call and provide the book's author:
curl \
-H "Content-Type: application/json" \
https://www.example.com/api/book/123`
Let's study how the GraphQL request will achieve the same thing more efficiently.
In GraphQL, the
query
operation performs theGET
function of REST.In GraphQL, users don't have their own endpoint. The
/graphql
endpoint receives all requests.We supply the pertinent parameters to the
query
operation and specify the Query we are interested in to specify what data we are interested in.
The curl request will look like this:
curl -g \
-X POST \
-H "Content-Type: application/json" \
-d '{"query":"{getAllBooks {id author title }}"}' \
http://localhost:8080/graphql
However, GraphQL also has its downside; unlike REST's POST/PUT
requests, GraphQL does not support file uploading. Using it in a simple application is not recommended because it adds complexity to your project.
Web caching is easier to access because of the many endpoints and REST calls' conformance to HTTP semantics, meaning web caching with GraphQL is more challenging due to its single endpoint.
The number of queries made and the total amount of data transferred are both decreased by GraphQL. But you should always consider the expense of integrating a GraphQL client into your frontend.
REST API vs. GraphQL - Summary Table
To give you a better idea, here is a summary table of a few key differences between GraphQL and REST API:
S/N | Point | GraphQL | REST |
1. | Architecture | client-driven | server-driven |
2. | Organized in terms of | Schema & type system | endpoints |
3. | Operations | Query, Mutation, Subscription | Create, Read, Update, Delete |
4. | Data fetching | Specific data with a single API call | Fixed data with multiple API call |
5. | Community | growing | large |
6. | Performance | fast | longer due to multiple network calls |
7. | Development speed | rapid | slower |
8. | Learning curve | difficult | moderate |
9. | Stability | Less error prone | Better for complex queries |
10. | Use cases | Multiple microservices mobile apps | Simple apps resources-driven apps |
11 | Error handling | Not easy | Error handling is simpler |
12. | Documentation | GraphQL uses GraphiQl for documentation | REST provides a variety of options for automated documentation |
Similarities between GraphQL and REST
Some of the similarities between GraphQL and REST:
GraphQL and REST can tell whether an API is intended to write or read data.
They both rely on frameworks and libraries
They both support statelessness.
Both of them communicate back and forth between server and client programs using HTTP protocols.
They both use JSON data formats - Data fetched by an HTTP GET request is usually returned in JSON format.
Which is Better GraphQL or REST?
GraphQL employs a single endpoint for every operation, unlike REST APIs. Only GraphQL queries can be used to interact between GraphQL-based servers. It is possible to send GraphQL queries via a REST client, such as Axios or get(), for straightforward projects.
Most of the differences, I believe, favor GraphQL. I think it's particularly remarkable that you can implement your API as a collection of small resolver functions and then send a complex query that retrieves multiple resources at once in a predictable manner. This saves the API implementer from creating numerous endpoints with different shapes and allows the API consumer to avoid fetching unnecessary data.
Conclusion
In many ways, GraphQL is superior to REST, as I hope you can see from this essay. The initial setup of GraphQL might take longer; however, there are several scaffolders that make that task simpler. And even while it initially requires more effort, it is completely worthwhile because it offers you long-term benefits.
Thank you for taking the time to read this article, and I hope you enjoyed it! ♥️♥️❤️