DEV Community

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

Posted on • Edited on

4 reasons why you should use GraphQL over REST APIs

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

Latest comments (77)

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

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.

 
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
 
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
 
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
 
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
 
bevilaquabruno profile image
Bruno

Nice title change, now the article is perfect 😊!

Collapse
 
blessinghirwa profile image
Blessing Hirwa

Haha, thanks πŸ˜€.

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