REST has been preferred by many developers to send data over HTTP
because they didn't need to install additional software or libraries when creating an API
though GraphQL
is ordinarily introduced as a technology to replace the legacy of REST APIs
. In this article, I’ll be explaining the benefits, limitations, and differences between these two, which will help you decide what to chose for your next project. So without further ado let's dive right into it.
What is REST?
REST(Representational state transfer) is an architectural style for providing standards between computer systems on the web, making it easier for systems to communicate with each other. With REST
you separate the implementation of client and server, to achieve this we use stateless operations including (GET
, POST
, PUT
, and DELETE
) to send and receive resources.
The idea behind this REST
architecture is that you would retrieve a resource by putting through a request to the resource’s URL and get a response (usually JSON
, but it depends on the API
).
Benefits of REST
Rest is scalable as it separates the client from the server and gives you ability to scale your application with ease.
Flexibility is another advantage of REST as
Data
is not tied to resources or methods, so REST can handle different types of calls and return different data formats.
Limitations of REST
Over fetching: This is when the API endpoint provides way more information than required by the client.
Under fetching: This is when the API endpoint doesn’t provide all of the required information. So, the client has to make multiple requests to get everything the application needs.
We'll use an example to understand well the above concepts
What is GraphQL?
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. In addition to this, it lets you combine different entities into a single query.
Benefits of GraphQL
Retrieve precise data, and nothing extra. In GraphQL, you get what you request and nothing more, which is good.
Faster development in the Client. Usually, when there are changes in the data requirements, you would just need to modify the query and there isn’t much change required, thus allowing rapid product iterations. Both the client and server development teams can work independently, as long as both the teams know the structure of the data. i.e client and server implementations are independent to each other.
Example comparing both of them
Let’s suppose, for example, we are displaying a user’s feed with a list of the user’s post and his/her followers. In our case, we have to display the author of the post, the posts as well as the followers for that user.
If we were to use REST
, we would have made at least 2 or 3 requests, similar to this:
-
/user/<id>
to get the User(Author) details likely the username. -
/user/<id>/posts
to get the list of posts posted by that user. -
/user/<id>/followers
to get the list of followers for that specific user.
But in all these cases we are over-fetching the data. For example, in the first request, we need only the name, but we get all the details related to the user when we use this approach.
This is when GraphQL
shows it’s potential. We need to specify the query and we can get the desired output. To achieve the same using GraphQL
, we can use a query similar to this:
query {
User(id: '123') {
name
posts {
title
}
followers {
name
}
}
}
By using such a query we will be able to get a JSON response with the following properties. Clean and Simple, right?
GraphQL vs REST
To sum up, here are some couple of standout differences between GraphQL
and REST
:
1. Data fetching
REST
causes over-fetching or under-fetching, whereas this isn’t the case with GraphQL
. In GraphQL
, What you ask for is what you get.
2. Object definition (JSON response)
In REST
you can define the request object
on the Backend
and in GraphQL
you define the object on the Frontend
.
3. Automatic caching
REST
automatically puts caching into effect whereas GraphQL
has no automatic caching system, but using clients such as Apollo Client, Relay, etc. will make caching possible. Caching enables your client to respond to future queries for the same data without sending unnecessary network requests
4. Error Handling
Error handling in REST
is much simpler as compared to GraphQL
, which typically gives you a 200 OK
status code
, even if there’s an error
. But, when using clients such as Apollo Client, Relay, etc
, it is very much possible to handle errors easily.
GraphQL works best for the following scenarios
Apps for devices such as mobile phones, smartwatches, and IoT devices, where bandwidth usage matters.
Applications where nested data needs to be fetched in a single call.
A composite pattern, where an application retrieves data from multiple, different storage APIs.
Conclusion
GraphQL
certainly has many advantages over REST
, but it might not always be the best implementation. Like I said earlier, the choice depends on your application, whether to choose REST
or GraphQL
.
I hope this might help you make decisions in your future projects. If you like to share your experiences about GraphQL
or REST
, drop them in the comments section. Don't forget to connect with me on Twitter and
Linkedin. Thank you for reading 😊!
Top comments (77)
I think the title is wrong, it should be more like "difference b/w graphql and rest". You can't just say to stop using one over the other. Both have their own benefits.
Also, the content of this post is more like telling the difference.
My point here was to show how Graphql can make your work more easier. I also said that Graphql is not always the best solution.
The title of your article is literally, "4 reasons why you should use GraphQL over REST APIs" and your slug is, "stop-using-rest-for-apis-53n".
Also, GraphQL has many drawbacks, none of which you really mentioned. What about the N + 1 problem? Or having to use and/or implement DataLoader?
In the middle of the post I said that it is difficult to implement caching and that it's not always the best solution.
he changed it now :).
His article, his rules. He wants the title to be like that, let him name the article like that.
and keep on feeding the click-bait culture? Siddhant just made a senseful suggestion
While I'm not in the position to say this, but he might be writing for his future self.
you can save a note on your laptop for that. Here many junior developers come to look for resources, and in this case they can be fooled and confused and reach to GQL even to ping a server just because "stop using REST for APIs"
Just let it be, man.
I get you point, but in my conclusion I said that you must do a research before starting your project. GraphQL is not always the best solution.
+1
on point! ty
GraphQL is all cool and dandy until you have files to send over. I am aware that you can send it via blob, but who does store images as blobs in database??? I also held discussions about converting blobs on the backend or sending them over to the third parties that can handle it and store it as a file with url of the image in response. Took significant amount of time to process it all and that was just bad UX. Remember - your users are using your app and they don't really care what's under the hood.
REST API over fetching and under fetching can be resolved on the REST API, I am sure that you do it yourself if you are fullstack so you have control what is sent over which API route or if you are frontend, I know it is difficult, but please try to communicate with, you know, backend guy who handles the REST API routes. It's not so hard.
I have used both, both have their use cases. GraphQL for Jamstack sites is great, for much writing to the DB and especially for files handling I don't find it so attractive.
just my 2c
If your API is under or over fetching: You wrote a poor API method. It's not about REST vs New ShINy TeKS.
And where I haven't used GraphQL, I have used something with a similar concept ( OData) and everything about the concept to me, is weird and wrong.
The logic behind over fetching is that you can't specify which resources you want in REST, you get result and then filter it to get what you want.
If you need to filter data, you might be missing a route (for example getting a specific thing with
/api/things/:id
).You can also use path argument to filter out things (with
/api/things?group_id=23
) or even stick those arguments in the request's body.In this case you'll get all data related to
group_id=23
which is not needed. In our case we want to get only the post title that hasgroup_id=23
. ForREST
we get all data related to that group id but forGraphQL
we'll only get thevalue
that we asked for, nothing more.And this is why I say your API is bad, and it isn't on the fault of REST if this is your problem.
There's nothing wrong with simple methods, that return exactly what you need.
According to your case what do you think this API will return? I want us to be in the same line.
And also remember that here we're focusing on the amount of data to be returned.
I would expect a single or list of group ids that the user belongs to. Depending on what a group is, and if the user could be in multiple groups.
(as an off the cuff example).
using odata, and I believe GraphQL the query would look something like:
Which might perform just as well, but it's more than the UI should care about, and has some concerns.
Perhaps this is written instead:
where the SQL will now be very unoptimized:
Or perhaps they decide to filter on a non-indexed column (Since the UI doesn't know or care what columns are indexed).
And as much as we'd all like to say: "Code review" the truth is, I'm inheriting tech debt from dozens of coders around the world where this has slipped through the cracks.
The UI folks often don't know the intricacies of the API or DB. The expectation of the architecture should be forgiving enough that you can't write a really bad query. And IMO a good API along with using swagger is the ideal route.
Ideal isn't always best though, and I can see where someone might choose GraphQL:
But in the conclusion I said that Graphql is not always the best choice. You'll use it depending on the structure of your app and the type of data you want to play with. Makes sense?
It's pretty fair to say that GraphQL being primarily concerned with the query side of things lets you construct complex graph lookups by design. If anything it's also what makes it difficult to deal with on the backend side because of permissions, caching and such.
However, it's not fair to say REST doesn't allow granular selections when it doesn't at all cover whether or not you can return selective filtering or selective returns. It's entirely left up to the implementer, and if you follow a standard that's RESTful like jsonapi.org then partial selects and filtering is covered.
yes, but then GraphQL in this case is faster than REST. right?
Faster how? And faster than what exactly?
Faster than REST through EF 4? Maybe, possibly, even probably.
Faster than REST using Dapper or EF 6/7? Likely not. Assuming similar scope and queries.
I would be interested to see how some problems are solved in GraphQL, vs more traditional solutions.
Most of my original comment was also towards Ivan, and agreeing with his comment.
When I say faster I mean
data fetching
andlow bandwidth
Then it would certainly have more to do with specific implementations, not GQL over all REST implementations.
REST is after all, just a set of concepts. I'd a well designed RESTful service is faster than 90% of all GQL APIs.
If you put a well designed GraphQL API against a well designed REST API:
They probably tie overall. Sometimes they would be equal, sometimes each one would be faster.
Ideally, if I was debating between a new application and needed to decide between a webAPI and REST, vs GraphQL I'd consider:
Industry Support
Readability
Maintainability
Performance
RESTful APIs win 3/4 of those IMO. If performance became my only concern, I'd grab a demo database and do some hard testing. If GraphSQL won, but within a margin of error: I'd still pick REST because of it's other strengths.
I mean, I've recommend changes on tech stacks because of performance before.
EF 6 to EF 7: reduced queries by 50%.
EF 7 to Dapper: 75% reduction.
Those are huge performance gains. If GraphQL could do that for a given design, I'd be on it.
In fact, I am a little curious what I could do with it. But I suspect I can keep a RESTful service, using Dapper (I am a fullstack .NET guy) more performant than a graphql API...
It always depend on the kind of project you're building. But still at the end of the day you find both REST and GraphQL to be good.
Sending blob is not strange . you can do it also in REST, and inside backend you can convert it into file, store the name in database and file in your storage
You can add Content-Type to the response in REST, put the path directly to "src" attribute to your img.
I would say GraphQL has way more disadvantages over REST.
The inability to cache results (or if you manage to do so with forward caching proxy with lots of RAM and added latency) makes this only solution for systems that need no performance or scaling. Systems with hundreds, thousands or more clients or requests/second will suffer greatly and trash your cache by storing non-reusable GraphQL results.
GraphQL will more likely result in poor database performance as there is no way to optimize for all combinations of all database columns by indexes. Either you create wide tables (by de-normalizing them) covering every possible column combination by an index causing heavy disk usage and your database INSERTs to take seconds instead of milliseconds or you normalize your database and cause tens or hundreds of JOIN operations. In either case there's no optimization possible with GraphQL as the model is created at the front-end without back-end developer interaction and his/her possibility to optimze for performance.
Since support for HTTP Push in HTTP/2 and HTTP/3 is now killed in the RFC draft your options for size and performance optimized REST calls are basically
sparse fieldsets
or for better cacheabilitypartials
.Just to chip in on caching, caching seems to work here over at Spotify and we get a decent amount of requests/second. It's not perfect though and i's not straightforward but you can get somewhere with query hashing for instance.
Out of curiosity, how much dedicated cache storage your typical GraphQL cache server has?
hmnn im not sure, i think caching is mainly handled through its subsidiaries, so cant say to be sure. Bigger issue seems to be fanning out for requests, as one graphql request can potentially mean a lot of subsequent requests fanning out over multiple microservices.
Statistically as tiny as 5 column table (with 4 really usable columns as one of them is typically an identifier) has 120 (5 factorial) different ways to order columns in GraphQL query that produces 120 different cacheable queries with identical result that would in normal case be cached and reused but now is trashing your cache. This becomes more prominent in bigger team where everyone writes their own queries.
thats very academic, but just don't do that then. i haven't seen an impact yet on our side, but what you are saying is probably true, sounds like the caching approach should be different, e.g. order on the fly. not saying its not a problem, i'm just saying were not having that problem, yet.
Or actually thinking about it, sounds like maybe caching in the wrong place, just cache the most used case and then sort on all the results? Otherwise i guess yeah you would need to cache for all those cases, taking up space.
I am not sure about what you said, in this repository we have cache on graphql : github.com/graph-gophers/graphql-go , it is not about topology , it is about the package that you are using.
Do you have stats about hit ratios on your cache? It's most probably trashing. It's enough to swap 2 fields in a model or leave one out and you cannot reuse the cache. Also if you accidentally do not keep the order of fields as they are defined in the database index or add one extra field you cannot use the index and you pay by slow table scan performance. What's the point giving someone all the possible flexibility on the fronted when it results in 99.9% times in performance issues?
I got your point, maybe you can not cache everything 100% because of the huge data in queries, but it is not because of the topology of Graphql. graphql.org/learn/caching/
I'd also add:
It puts too much logic and control on the client / UI.
I have seen these "REST vs. GraphQL" articles lately a lot and was thinking that it might not be that black and white. I believe that both concepts have their benefits and can work quite well together. Why not using a 2-tier architecture where REST is used for the internal systems (e.g. a back-office application that doesn't need that much speed) and GraphQL is used for the customer-centered apps? The caching ability of REST might be useful if you for example have a slow running legacy service. You could request parts of the GraphQL query via REST and get the cached result instead of waiting for the legacy service.
tl;tr: I believe both play well together and would love to see more articles about how to use them useful together.
will make more about it soon.
Thanks for the article.
I just wanted to mention that a lot of your benefits are based on implementation details in regard to specifically GraphQL. Over and under fetching is and can be an issue with GraphQL too, especially when it sits between the client and microservices. I don't really get your object definition point, i also think that might be an implementation detail you don't have to do. Could you expand on this? Caching can again be an implementation detail, REST can also fail to cache.
I think you are looking maybe too much from an implementation effort, i'm wondering what your thoughts are based on it from an solution oriented point of view? For instance the fact that GraphQL could be a good fit for many clients, or around versioning? I would love to hear your thoughts
Here are some use cases of GraphQL:
-Apps for devices such as mobile phones, smartwatches, and IoT devices, where bandwidth usage matters.
-Applications where nested data needs to be fetched in a single call.
-A composite pattern, where an application retrieves data from multiple, different storage APIs.
The last two bullets, why would you not do it with REST? Especially the last one im wondering what the benefit is of choosing GraphQL? Is it convience, because the data loaders are already there?
On the second last bullet about nested calls we can suppose that we blog or social networking platform where posts need to be fetched along with nested comments and details about the person commenting. You can also refer to the example provided in the article.
On the last bullet point we can suppose that we have a dashboard that fetches data from multiple sources such as logging services, backends for consumption stats, and third-party analytics tools to capture end-user interactions.
Hope this answers your question.
Not really sorry, the first can be done as well with REST, if you would include all that info in the request for the post right? or is that not very RESTy? The last bullet i also still don't completely understand. A backend using rest could still easily consolidate those services?
GraphQL allows multiple resource requests in a single query call, which saves time and bandwidth by reducing the number of network round trips to the server. It also helps to prevent waterfall network requests, where you need to resolve dependent resources on previous requests. For example, consider a blog’s homepage where you need to display multiple widgets, such as recent posts, the most popular posts, categories, and featured posts. With REST architecture, displaying these would take at least five requests, while a similar scenario using GraphQL requires just a single GraphQL request.
If you put all of the requests in one
API
then you'll to write many lines of code compared toGraphQL
and it'll increase execution time. The goal here is to make thingssimple and fast
.I understand that this is always touted as a big plus of GraphQL, but it's absolutely possible to do this with a REST API, check out the spec for JSON:API, which allows nested entity relationships to be defined as part of a single request.
That aside, if you have control over the API you're querying, there's no reason you can't define an endpoint that includes all the data you need in a single request anyway, right?
REST can do it but Graphql uses low bandwidth compared to REST, that was my point.
I have no idea how can GraphQL possibly do this with lower bandwidth. It sounds exactly the same to me regardless of which way you fetch data
The reason behind this is that when you fetch few data then the bandwidth will decrease as there will be a few data to download.
I think the parent comment might be asking why using GraphQL instead of REST would result in fetching less data. There's nothing about a REST API specifically that means more data would be sent than with a GraphQL API. Only a poorly designed REST API that sends huge amounts of data unnecessarily would have this issue.
All GraphQL does is move the problem to the frontend, now it's up to a frontend developer, rather than the API developer, to determine how much data is needed. Meanwhile, the API developer also has to ensure that any possible combination of data structure can be efficiently returned from the API rather than preset structures which can be optimised and cached.
With that said, if you're building a data heavy system, where the user of the frontend has lots of interactivity, GraphQL could make requests more efficient by only requesting the data the user has asked for. Data heavy tables and large, interactive charts could certainly see a bandwidth benefit. But with that benefit, you lose the ability to cache responses (meaning you could end up fetching more data overall) and gain an additional performance overhead on the server.
Nice 😄, I have heard
GraphQl
has many good features compared toREST
.Post Title can mislead beginners to completely stop using
REST
which is not what you mean i know. By the way title example like , UseGraphQl
to create modern APIs, may be good, Just a suggestion:)Finally its not between
REST
orGraphQl
Always use best tool for the Job.Good suggestion.
Hell no. Having used both graphql and rest apis, graphql is NOT a silver bullet. It has many downsides (harder to debug from the browser, terrible error handling, more complicated to build security rules around certain days points, etc), and only one big advantage: neer infinite customizability of requests by the client code.
If you are making a public API with a wide range of consumers and possible use cases, graphql is a good choice to consider. If you're creating an API that's only being used by your apps, or has limited use cases, stick with traditional REST. They are different tools for different jobs.
yes, that's why I mentioned use cases for Graphql and said that Graphql is not always the best solution.
I like the idea of GraphQL. I find building resolvers properly with good caching is something that most people don't do (causing worse performance).
It also encourages building a monolith. With RESTful APIs it is easier to deploy smaller services or microservices.
Now, you can use federation or just really lean on your developers to not reach into other services. What I mean by this, say you have a e-commerce site. With RESTful you might have APIs that cover Account, Cart, and Payment. The cart API might call the Payment and Account APIs. I keep seeing GraphQL developers just reaching into the other domain's code. The cart calls the code from Account and Payment (or worse, reaches directly into the database).
I realize this really isn't a fault with GraphQL itself, but more around development patterns. Still, almost every tutorial is teaching developers to build tightly coupled monoliths that at enterprise scale is not a great pattern.
This is good and I like it so much. I am a high fun of GraphQL with the way that you have a single endpoint is also a property I like. However, GraphQL has yet several accounts to improve before deciding that it is better than Rest. File Handling has been a headache for most of developers in GraphQL. Rest has its good and works better when you are working on big projects. While GraphQL would need to be preferred when related data is needed and not such a big application.
You’re right. Graphql is improving as years go by and I think for now someone can use them together as one is good at one thing than the other.
No offense but this title alone just kind of makes it seem like you don't have much of an understanding of the topic either. GraphQL is a lot different than REST APIs, you can't use GraphQL "for" REST APIs.
Some comments have been hidden by the post's author - find out more