GraphQL VS REST — Which one to choose when? | SoluteLabs
REST as an API standard has evolved over the past few years, and GraphQL has slowly emerged as an architecture of choice among the developers due to its advantages. Before we dive into the debate of GraphQL vs. REST, let’s brush up a bit on our basics.
An API (Application Programming Interface) is the intermediary that lets two software applications to talk to each other. An API dictates how a client can load data from a server.
GraphQL helps specify precisely what data it needs from an API, which is called declarative data fetching. Now that we have the basics in place let us see how REST and GraphQL came into being.
REST — is History?
REST stands for “Representational State Transfer.” It is a set of rules that determines how an API looks like. One of these rules dictates that you should get a resource (a piece of data) when you link to a specific URL.
The URL is called a request, and the data sent back is called a response.
When you call a RESTful API, the server will transfer the representation of the state of the resource to the client.
For example, if you call the Facebook Profile API to fetch a specific user, REST will transfer the state of that user, including name, profile picture, latest posts, and more.
To perform an operation in REST, you need to call it in the form of an HTTP request, such as GET, POST, PUT or DELETE. For example, to get the Facebook profile of a particular user, you will need the URL that identifies that user and the HTTP method GET.
Now that you know the basics of REST let’s see how GraphQL came into existence and how it evolved.
GraphQL — Better than the REST?
While RESTful APIs provided a great new way of computers to interact with one another, there were also a few hiccups that made developers look elsewhere.
For starters, RESTful APIs returned more data than what was needed, meaning more API calls. Since every endpoint could return only the specified data, developers had to design endpoints keeping the front-end views in mind.
All this resulted in less flexibility, and Facebook engineers decide to build an alternative to REST. GraphQL was built by Facebook in 2012 and was made open source in 2015.
GraphQL describes how you can communicate with a server and transfer data from a client to a server. It differs from REST fundamentally due to the fact that the client can specifically ask what data it needs.
GraphQL makes it easy to source and aggregate data from multiple sources. Instead of multiple endpoints, you had a “smart” endpoint that can collect complicated queries and present the output in whatever format the client requires.
We will tell it to you with the help of a metaphor. Imagine you have to order food from your cafe, buy groceries, and borrow a book from a library. With REST, you will be making three different phone calls, which are three requests.
With GraphQL, these three phone calls can be replaced by a single one, like talking to Siri. All you have to do is tell the address to these places, and then place your order (“fetch me a Cappucino, a loaf of bread, and a copy of today’s Herald.”)
This is a very rudimentary way to look at how GraphQL works, but it serves the purpose. We will now see how GraphQL and REST are similar.
Similarities between GraphQL and REST
GraphQL and REST essentially accomplish the same task, i.e., communicate with a server and retrieve data. Here are a few similarities between the two:
- Both GraphQL and REST are based on the concept of a resource, and they specify IDs for those resources.
- Both GraphQL and REST rely on frameworks and libraries to handle the tiny networking details.
- Both can differentiate if an API request is intended to read data or write it.
- Endpoints in REST API are similar to the list of fields on Query and Mutation types in GraphQL.
Where does GraphQL far better than REST
We have seen how GraphQL and REST are almost similar, but GraphQL does score a few brownie points over REST. These include situations like Over-fetching and Under-fetching of data and faster Front-end development. Let us take a look at these in detail.
Take a simple blog as an example. If you want to show all the latest posts on the front page, your REST query will look like this:
Now, if you want to return the author as well, you have three methods in REST.
The first method is to fetch the authors from another resource.
The code to accomplish this task will look like this:
1. UNDER-FETCHING
If you use the above method, you will have made two server requests instead of one. This may not look like a problem at this stage, but as you continue to scale the app, there will be multiple requests to the server to different endpoints in order to fetch all the data.
The REST API endpoint may not have all the data that an application needs, and so it doesn’t get everything the application needs in one data fetching exercise. This is called under-fetching.
Meanwhile, if you use GraphQL to solve the same problem, the code will look like this.
As you can see, there is only one request to the server, and there are no multiple round trips to slow down the server. This is one of the prime benefits of GraphQL.
2. OVER- FETCHING
Another method to retrieve the author’s data in REST is to modify the resource also to return the author.
The code for accomplishing this in REST will look like:
Changing this resource may have a secondary effect at another place in your application, something you may not have considered.
If you want to add a sidebar in the case of our blog, that also shows the top monthly posts with their titles, subtitles, and date, using the resource /api/posts we created earlier.
We have modified this resource, and now the sidebar shows the author as well, which we don’t need. This fetching of useless data is a major concern for users who have limited data plans.
GraphQL, on the other hand, fetches only the data that we need, so a GraphQL query to solve this problem will look like
As you can see, even if we add a sidebar, this query will return only the required data.
Apart from data fetching, GraphQL also speeds up development on the front end.
3. FASTER FRONT-END DEVELOPMENT
There is a third way to solve the problem of retrieving posts with the relevant author’s name, which can be done in REST by creating a new resource that returns the posts with the author.
So to create a new resource, the code in REST will look like:
But the problem with this approach is that each new specific view needs a specific endpoint. When the view needs a new data, the development has to slow down until you update the endpoint.
This problem can be overcome by GraphQL since it fetches only the required data.
Nothing slows down. All you have to do is add a new field to the existing query. So the GraphQL code to accomplish this will look like:
As you can see, all we did was add a couple of lines to the existing GraphQL code.
The client has much more freedom with the data fetched using GraphQL, so we can get around developing our page much faster.
Where does REST still hold its mettle?
While we have stated all the benefits of GraphQL, there are a few benefits of using REST that also deserve mention.
These advantages include:
- Code vulnerability in GraphQL: GraphQL lets you retrieve the exact data that you want from the server, which leads to a tricky security issue. If an attacker wants to carry out a DDoS (Denial-of-service-attack) to an unprotected server, all he has to do is execute an expensive nested query to overload your server. This is not the case with REST, where you use separate HTTP calls to extract data.
- Error Reporting: With REST, you can use API responses and build a monitoring system for error messages. But error reporting in GraphQL leaves a lot to be desired, with the ubiquitous “200 K Error — Something went wrong” message.
- HTTP caching issue: HTTP caches are used by modern browsers to identify resources and make sure no two resources are the same and avoid refetching. With GraphQL, there is no way to use a universal identifier because we use the same URL for all the requests. You have to set up your own cache in GraphQL, which is tiresome.
Now that you have seen both the pros and cons of GraphQL and REST, you might have a question that many developers face.
Which among GraphQL and REST should I use to build my website?
The answer is highly subjective and depends on a host of factors.
If your API is intended to be used on a mobile application, use GraphQL since it offers better bandwidth usage.
If you need caching and monitoring facilities in your API, use REST.
This being said, you can also use a combination of GraphQL and REST for a project. It all depends on your data and performance requirements. To make matters clear, get in touch with us here at SoluteLabs, and we would love to set up a discovery meeting.