DEV Community

loading...
Cover image for 4 reasons why you should use GraphQL over REST APIs

4 reasons why you should use GraphQL over REST APIs

blessingartcreator profile image Blessing Hirwa Updated on ・4 min read

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
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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 😊!

Discussion (73)

pic
Editor guide
Collapse
siddhantk232 profile image
Siddhant Kumar

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.

Collapse
blessingartcreator profile image
Blessing Hirwa Author

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.

Collapse
peterdonovan profile image
Peter Donovan

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?

Thread Thread
blessingartcreator profile image
Blessing Hirwa Author

In the middle of the post I said that it is difficult to implement caching and that it's not always the best solution.

Collapse
oliverleitner profile image
Oliver Leitner

i hear you, it helped me already alot...
i usually draw the line at the size of the thing im working at. for small stuff a simple query string to the interface is often enough.

Thread Thread
blessingartcreator profile image
Blessing Hirwa Author

yeah, sometimes it's not appropriate to use GraphQl for small tasks as for REST works well on small tasks.

Collapse
muhyilmaz profile image
MUHAMMED YILMAZ

he changed it now :).

Collapse
highcenburg profile image
Vicente G. Reyes

His article, his rules. He wants the title to be like that, let him name the article like that.

Collapse
clivend profile image
clivend

and keep on feeding the click-bait culture? Siddhant just made a senseful suggestion

Thread Thread
highcenburg profile image
Vicente G. Reyes

While I'm not in the position to say this, but he might be writing for his future self.

Thread Thread
clivend profile image
clivend

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"

Thread Thread
highcenburg profile image
Vicente G. Reyes

Just let it be, man.

Thread Thread
blessingartcreator profile image
Blessing Hirwa Author

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.

Collapse
thesanjeevsharma profile image
Collapse
janpauldahlke profile image
jan paul

on point! ty

Collapse
pozda profile image
Ivan Pozderac

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

Collapse
nimahkh profile image
Nima Habibkhoda

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

Collapse
mk0y8 profile image
Marko Jakic

You can add Content-Type to the response in REST, put the path directly to "src" attribute to your img.

Collapse
athomsfere profile image
Austin French

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.

Collapse
blessingartcreator profile image
Blessing Hirwa Author

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.

Thread Thread
drarig29 profile image
Corentin Girard

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.

Thread Thread
blessingartcreator profile image
Blessing Hirwa Author

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 has group_id=23. For REST we get all data related to that group id but for GraphQL we'll only get the value that we asked for, nothing more.

Thread Thread
athomsfere profile image
Austin French

And this is why I say your API is bad, and it isn't on the fault of REST if this is your problem.

  GET /GroupId?UserName=jsmith1958
Enter fullscreen mode Exit fullscreen mode

There's nothing wrong with simple methods, that return exactly what you need.

Thread Thread
blessingartcreator profile image
Blessing Hirwa Author

According to your case what do you think this API will return? I want us to be in the same line.

Thread Thread
blessingartcreator profile image
Blessing Hirwa Author

And also remember that here we're focusing on the amount of data to be returned.

Thread Thread
athomsfere profile image
Austin French

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:

GET /Groups?$filter=UserName eq 'jsmith1958` & $select='groupId'
Enter fullscreen mode Exit fullscreen mode

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:

GET /Groups?$filter=UserName like 'jsmith1958`
Enter fullscreen mode Exit fullscreen mode

where the SQL will now be very unoptimized:

 SELECT * FROM GROUPS
     WHERE UserName LIKE '%JSMITH1985%'
Enter fullscreen mode Exit fullscreen mode

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:

  1. Prototyping
  2. Rapid Development
  3. New Applications with relatively narrow scope
Thread Thread
blessingartcreator profile image
Blessing Hirwa Author

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?

Thread Thread
kitsunde profile image
Kit Sunde

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.

Thread Thread
blessingartcreator profile image
Blessing Hirwa Author

yes, but then GraphQL in this case is faster than REST. right?

Thread Thread
athomsfere profile image
Austin French

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.

Thread Thread
blessingartcreator profile image
Blessing Hirwa Author

When I say faster I mean data fetching and low bandwidth

Thread Thread
athomsfere profile image
Austin French

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...

Thread Thread
blessingartcreator profile image
Blessing Hirwa Author

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.

Collapse
slavius profile image
Slavius

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 cacheability partials.

Collapse
kfwerf profile image
Kenneth van der Werf

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.

Collapse
slavius profile image
Slavius

Out of curiosity, how much dedicated cache storage your typical GraphQL cache server has?

Thread Thread
kfwerf profile image
Kenneth van der Werf

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.

Thread Thread
slavius profile image
Slavius

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.

Thread Thread
kfwerf profile image
Kenneth van der Werf

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.

Collapse
nimahkh profile image
Nima Habibkhoda

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.

Collapse
slavius profile image
Slavius

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?

Thread Thread
nimahkh profile image
Nima Habibkhoda

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/

Collapse
athomsfere profile image
Austin French

I'd also add:
It puts too much logic and control on the client / UI.

Collapse
janhommes profile image
Jan Hommes

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.

Collapse
blessingartcreator profile image
Blessing Hirwa Author

will make more about it soon.

Collapse
kfwerf profile image
Kenneth van der Werf

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

Collapse
blessingartcreator profile image
Blessing Hirwa Author

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.

Collapse
kfwerf profile image
Kenneth van der Werf

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?

Thread Thread
blessingartcreator profile image
Blessing Hirwa Author

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.

Thread Thread
kfwerf profile image
Kenneth van der Werf

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?

Thread Thread
blessingartcreator profile image
Blessing Hirwa Author

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 to GraphQL and it'll increase execution time. The goal here is to make things simple and fast.

Thread Thread
andrewbridge profile image
Andrew Bridge

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?

Thread Thread
blessingartcreator profile image
Blessing Hirwa Author

REST can do it but Graphql uses low bandwidth compared to REST, that was my point.

Collapse
craigmiller160 profile image
Craig Miller

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.

Collapse
blessingartcreator profile image
Blessing Hirwa Author

yes, that's why I mentioned use cases for Graphql and said that Graphql is not always the best solution.

Collapse
shaijut profile image
Shaiju T

Nice 😄, I have heard GraphQl has many good features compared to REST.

Post Title can mislead beginners to completely stop using REST which is not what you mean i know. By the way title example like , Use GraphQl to create modern APIs, may be good, Just a suggestion:)

Finally its not between REST or GraphQl Always use best tool for the Job.

Collapse
blessingartcreator profile image
Blessing Hirwa Author

Good suggestion.

Collapse
brianmcbride profile image
Brian McBride

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.

Collapse
mraboutin profile image
Alex Boutin

Thats a good article about difference between GarphQL and REST yes, but it is more of a clickbait title, just like Siddhant said. You adress one problem of REST, wich can happen only if you cannot make changes to the API, wich you solve by creating doing the said changes on GraphQL? this use case doesn't make sense for me. Yes GraphQL can be nice for some case, just like some poeple like using NoSQL DataBase, but with bigger scenarios, it becomes way harder and less time efficient to rely on different solutions (Solutions that keep being improved with time and will get replaced one day indeed, but it's never White or Black, some things are better suited for different problem, thats all)

Collapse
blessingartcreator profile image
Blessing Hirwa Author

yes, that's why I mentioned use cases for Graphql and said that Graphql is not always the best solution.

Collapse
nyakurilevite profile image
Nyakuri Levite

Thank you for your article i have changed my mind about GraphQL

Collapse
blessingartcreator profile image
Blessing Hirwa Author

Glad it helped.

Collapse
bevilaquabruno profile image
Bruno Fernando Bevilaqua

Nice title change, now the article is perfect 😊!

Collapse
blessingartcreator profile image
Blessing Hirwa Author

Haha, thanks 😀.

Collapse
alexneamtu profile image
Alex Neamtu

What are the disadvantages of graphql? (Nested level count maybe?)

Collapse
blessingartcreator profile image
Blessing Hirwa Author

It has some limitations. One of them is that implementing caching is complicated compared to REST.

Collapse
alexneamtu profile image
Thread Thread
kitsunde profile image
Kit Sunde

If you have a system with resource policies. Like say level 1 customer support can only see customers numbers, account balances, but not individual orders, PII or inventory levels.

You'll have another kind of fan out complexity since you can just reach across the whole graph, you need to propagate policy decisions in some maintainable manner when the queries aren't just localised to just say the accounts balance endpoint itself.

GraphQL API migrations like renaming fields and restructuring is also left as an exercise to the reader. The answer commonly thrown around is "but you shouldn't", which of course you'll need to eventually have breaking changes it just avoids some struggles of RESTful API's.

All solvable problems obviously, but if you don't already have good answers, but do have a complex domain to deal with I wouldn't try until I understand exactly what I should do.

Thread Thread
alexneamtu profile image
Alex Neamtu

I love graphQL, not using it now, but I can't wait to use it again.
What I'm trying to say is that it has its downfalls.

Collapse
muhyilmaz profile image
MUHAMMED YILMAZ

You make a versus but not clear. Anyway i will search GraphQL. Thanks

Collapse
artydev profile image
artydev

Hy all,
You can also look at the grpc protocol
Regards

Collapse
vladi160 profile image
vladi160

This is not true: "REST causes over-fetching or under-fetching".
"In REST you can define the request object on the Backend and in GraphQL you define the object on the Frontend." - what means that ?

Some comments have been hidden by the post's author - find out more