DEV Community

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

4 reasons why you should use GraphQL over REST APIs

Blessing Hirwa on January 05, 2021

REST has been preferred by many developers to send data over HTTP because they didn't need to install additional software or libraries when creatin...
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
 
blessinghirwa profile image
Blessing Hirwa

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
 
darkfusion 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
 
blessinghirwa profile image
Blessing Hirwa

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
 
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
 
mrvaa5eiym profile image
mrVAa5eiym

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
 
mrvaa5eiym profile image
mrVAa5eiym

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
 
blessinghirwa profile image
Blessing Hirwa

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
Sanjeev Sharma

+1

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
 
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
 
blessinghirwa profile image
Blessing Hirwa

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
 
blessinghirwa profile image
Blessing Hirwa • Edited

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 • Edited

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
 
blessinghirwa profile image
Blessing Hirwa

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

Thread Thread
 
blessinghirwa profile image
Blessing Hirwa

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
 
blessinghirwa profile image
Blessing Hirwa

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
 
blessinghirwa profile image
Blessing Hirwa

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
 
blessinghirwa profile image
Blessing Hirwa

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
 
blessinghirwa profile image
Blessing Hirwa

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
 
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
 
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 • Edited

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
 
blessinghirwa profile image
Blessing Hirwa

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
 
blessinghirwa profile image
Blessing Hirwa

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
 
blessinghirwa profile image
Blessing Hirwa

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
 
blessinghirwa profile image
Blessing Hirwa

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
 
blessinghirwa profile image
Blessing Hirwa

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

Thread Thread
 
ozzythegiant profile image
Oziel Perez

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

Thread Thread
 
blessinghirwa profile image
Blessing Hirwa

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.

Thread Thread
 
andrewbridge profile image
Andrew Bridge

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.

Collapse
 
shaijut profile image
Shaiju T • Edited

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
 
blessinghirwa profile image
Blessing Hirwa

Good suggestion.

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
 
blessinghirwa profile image
Blessing Hirwa

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

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
 
didiermunezer38 profile image
Didier Munezero

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.

Collapse
 
blessinghirwa profile image
Blessing Hirwa

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.

Collapse
 
shadowtime2000 profile image
Info Comment hidden by post author - thread only accessible via permalink
shadowtime2000

4 reasons why you should use GraphQL for REST APIs

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.

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
 
blessinghirwa profile image
Blessing Hirwa

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

Collapse
 
alexneamtu profile image
Alex Neamtu • Edited

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

Collapse
 
blessinghirwa profile image
Blessing Hirwa

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

Collapse
 
alexneamtu profile image
Alex Neamtu

👍

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.

 
blessinghirwa profile image
Blessing Hirwa

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

Collapse
 
nyakurilevite profile image
Nyakuri Levite

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

Collapse
 
blessinghirwa profile image
Blessing Hirwa

Glad it helped.

Collapse
 
vladi160 profile image
vladi160 • Edited

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 ?

Edit:

The heading must be "why you should not use".
Don't use something, just because it is a hype.

The advantages of GraphQL are the same and for REST .
The disadvantages of REST are the same and for GraphQL

  • "Limitations of REST - Over fetching" - then don't over fetching
  • "Limitations of REST - Under fetching" - then don't under fetching

It is just a POST request to the same URL, nothing fancy.
May be, the packages for GraphQL are advantage like state management, but you can use the most popular of them with REST API, too.

Collapse
 
bevilaquabruno profile image
Bruno

Nice title change, now the article is perfect 😊!

Collapse
 
blessinghirwa profile image
Blessing Hirwa

Haha, thanks 😀.

Collapse
 
muhyilmaz profile image
MUHAMMED YILMAZ

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

Collapse
 
artydev profile image
artydev • Edited

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

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