loading...
Cover image for Why GraphQL?

Why GraphQL?

saranshk profile image saransh kataria Updated on ・6 min read

Originally published at https://www.wisdomgeek.com on June 2, 2020.

Developing APIs for the web has never been an easy task for developers. REST has been the defacto standard for designing web APIs for the last decade. Considering REST’s wild popularity, the first question that pops into anyone’s head when they start reading about GraphQL is: Why GraphQL? Why do we need GraphQL when developers are already well versed with RESTful architecture?

While GraphQL is the new kid on the block, and REST is the old person with lots of experience. We need to understand why GraphQL even came into existence. Before diving into the why let us first understand what.

What is GraphQL?

GraphQL stands for Graph Query language. It is a query language created by Facebook for Web APIs. It operates over HTTP, the same as REST. It is also to note that it is just a specification, not an implementation. That means we can implement it using any programming language we want with any database that we like, and any client we want while using GraphQL.

GraphQL is not an architectural pattern, nor a web service. It merely acts as a thin middle layer that enables declarative data fetching, giving the client the power to specify what data it needs. GraphQL is not a REST replacement, but an alternative. We can use it in combination with REST, or not, and that is up to us.

Where does GraphQL come into play?

The major focus of GraphQL is the optimization of network requests in order to fetch only the data that the client needs (preventing under-fetching and over-fetching). That was the key area that was being focussed on when GraphQL was being developed. This problem arose because the bar had been raised by the users who expect high-quality personalized experiences on all devices and platforms that they are using. REST endpoints were not good enough of a solution for such clients since REST is more of a point to point procedural API. And if a device wanted some specific data only, the developer either had to create another endpoint to return only the specific data. Or they had to add some boolean fields to the input parameters to specify what was needed. This ended up becoming way too complex to handle for large scale applications.

What problems with REST does GraphQL try to solve?

The major benefits of GraphQL are :

  • Speed
  • Flexibility
  • Easy to use
  • Simple to maintain
  • Developer-friendly

Let’s take a deeper look at how GraphQL tackles these.

GraphQL is faster

Let us see how we would architect a blogging application using REST.

For a simple blog post, like this one, we would need the details of the post that we need to display. So we will make a GET request for it. Let us assume the ID of this post is 1. Then we will make a request to an endpoint such as GET /posts/1 to get all the relevant details about this post.

But we also need the comments that anyone has made on this blog post. We will have to make another GET request for that too. That would look something like GET /posts/1/comments.

We also are showing some related articles down below. So we need another GET request for that. Let us assume we have an endpoint that takes the type of posts to be shown that takes a post id as a query string parameter. This would be another GET /posts?related=1.

This finally gives us everything we need to display this page. The whole process will look something like:

Now, if we were to fetch the same data from a GraphQL endpoint, we would not need so many HTTP requests. We will be querying a single endpoint (that would be /graphql). And we would be making a POST request to this endpoint, describing what all information we need from the server. In our case, we query for the post information, comments information, and related posts. We will be requesting these in the form of a GraphQL query.

We will not get into the specifics of the GraphQL query in this post since this is more about why GraphQL and not the how. But this is what it would eventually look like:

The important distinction is that instead of the server deciding what data gets sent back, the client describes what all it needs. The server then returns all of that information in a single request instead of having to make multiple requests.

There is no over fetching or under fetching of any data. Thus making GraphQL queries faster than REST.

GraphQL is flexible

This probably is the biggest advantage of GraphQL over REST.

We could have argued in the above example that we could have put all of the information that we needed in a single REST endpoint since we knew that all of those would be needed for a blog post. We could have crammed all of those into a single endpoint GET /posts which returns all the information that we needed, just like the GraphQL solution.

That approach would have been perfectly valid on its own. But what would happen if we wanted to add another thing in there? Say we wanted to show other posts by the author of this post? We would have had to change a lot of things in the endpoint that we created. And what if we wanted to show these conditionally? We would have to add another parameter in there as a query string.

Let us take another example, for the same endpoint. On a mobile device, we do not want to fetch the comments and the related posts. So we do not want to hit those endpoints until the user has scrolled to the bottom of the page. But we already crammed everything into a single endpoint for the desktop version. If we make a request to that endpoint, we are over fetching data and compromising on user experience.

GraphQL comes in super handy in these scenarios. Since the client describes what data it needs, GraphQL provides a flexible way to query the information needed. The query can be modified according to the client and according to the information needed on the page. If we need to get posts by author, we add that to the GraphQL query itself.

The client has the power to define exactly the data that it needs. Nothing more and nothing less.

GraphQL is simple to maintain and easy to use

As you have seen in the above examples, we would need to add a lot of new endpoints and query string parameters to the REST application to adapt a simple scenario such as blog posts.

But in the case of GraphQL, it is a single endpoint, with the client defining what it needs. Thus it becomes easier to maintain. The client can just change its query and the server will respond accordingly.

This approach does bring in its own challenges such as nested calls and other issues as well. But overall, it is generally more maintainable than REST endpoints.

GraphQL is developer-friendly

GraphQL also introduces a strongly typed system which allows you to avoid mistakes while fetching data.

The GraphQL query makes the query language a declarative way of defining and fetching data from the server. This helps understand what all data is being fetched from the server.

GraphQL also removes the hassle of maintaining separate versions of your API as long as your schema is backward compatible.

All of these points together lead to a great developer experience.

Is GraphQL going to replace REST?

While GraphQL has a lot of advantages over REST, it does not mean that GraphQL is the silver bullet. There are a lot of things that REST leverages that GraphQL cannot like HTTP Content types, HTTP caching, status codes, managing complex queries to ensure they are not making expensive joins, monitoring for endpoints, etc.

We need to understand the tradeoffs between the two and have both tools at our disposal. We can then select the correct one according to the application that we are building and its requirements.

If you are interested in knowing more about the complete stack, the React, Relay, and GraphQL ecosystem, you can check that post out.

Let us know in the comments about what you think about GraphQL. And if you would be using it in your next application?

Posted on by:

saranshk profile

saransh kataria

@saranshk

A curious full stack developer who loves challenges and getting things done.

Discussion

pic
Editor guide
 

For me the most important reson of using GraphQL is:
One models get big enough, overfetching and underfetching is a real issue

 

I don't really get why you cannot expose req.query.fields or req.body.fields in a REST API. I think OData is doing that.

Also, this idea integrates well with MongoDB projection.

Also, I don't know how much idempotency matters in GraphQL. (e.g. GET vs POST)

 

This post might be helpful in understanding the differences: jeffhandley.com/2018-09-13/graphql...

Too long, many links, more of the complaints and telling that the writer is trustworthy; so I still understand nothing.

Not to mention that GraphQL can also be DoS and injected as well.

 

Is idempotency an issue at all given that GraphQL only queries (reads) data? Or am I missing something here?

It has mutations , similar to a POST in old school REST only capable of dynamically handling a subset of the data you CAN post.

Thanks, I didn't know that. The "Query" in QL to me suggested otherwise.

 

Yeah, the "faster" argument is incorrect in my cases, and usually it's quite the opposite as a lot of transformations need to happen and on the other hand I can enforce specific stuff upon REST. Now getting less data might be faster for network but still slower to fetch from DB due to complexity of generating queries. Anyways depends on use cases, but the fact that I wish I could deliver both at the same time is coming from smartphone app team asking for this, and frontend constantly asking for that and wanting a way to fetch more stuff at once as they dislike 2 calls. However we benefit more from REST right now until we have more backend devs to provide both solutions

 

There is a learning curve for queries and how it is structured on the server side, and it does require efforts on the backend code but as you said, it's good to fetch all of it in 1 call instead of 2 and that is what makes it faster because of the HTTP request response time.

 

It shouldn’t be too hard to add caching for query results in the back-end, which does speed things up a lot. My CMS does this by default. (Craft CMS)

I haven’t noticed a significant performance penalty switching from REST to GraphQL, but maybe I’m just working on more simple apps. Performance totally depends on context here.

I have a plan to expand up to at least 6 services and 3 of those should be like "core" or something. Now having 1 gateway joining them it means all 3 will work in parallel but still a lot of network calls so 1 monolith is much faster in that case, and regarding the use case, REST is faster as I just respond to URL request instead of mutating stuff; since I'm using specific structure mutating would require building a lot of queries differently and more code and more checks than one might use with straight forward approach like just to apply some library on top of it. I dislike caching so not a way for me.

But the main point is if you have specific type of requests and responses and use DTOs instead of domain models, customised queries, and specific security (not role based but user based - each user has it's own resources) then you hit this point. So it's quite boring and complex way to notice this but it happens way more often than one might think especially in big projects / companies. In the end resource based is easier as you don't care about fields and either user or gateway on top of it filter out stuff - well last one usually ends up being GraphQL as gateway joining REST services :D

 

It also is a good fit when supporting multiple clients that have different data requirements.

 
 

I'm completely new to GraphQL but what do you guys think about the use case of publish-subscribe model and using GraphQL as a replacement for something like Firebase where you can send realtime data to clients who have subscribed. Or Am I not getting this right?

 

GraphQL subscriptions are probably what you are looking for. howtographql.com/graphql-js/7-subs... might be a good resource to get started.

 

@saransh kataria, thanks for the suggestion. I did know that's what I was looking for. I guess what I was trying to find out was people's opinion on it vs using something like Firebase. Any ideas?

It depends on your use case. I have used Firebase for a small application and it worked great, but it fell short on complex queries and did not have a sophisticated permissions system. I might be wrong since I did not use it a lot, but those two things made it a no go for bigger applications for me.

Makes sense. Thanks for the reply!

 

Nice post. My experience with interviews lately is that many companies are aware of the advantages of using graphQL (Apollo, et all), but they either don't have the know-how to add it or are locked into another approach.

 

When you say they don't know how to add it, you mean they know about GraphQL as a concept but have not implemented it? Could you elaborate a bit more on the specifics of that and being locked into an approach?

 

Sure. Most tech interviewers have heard of GraphQL, that's universal. I have only talked to a handful that have a full blown implementation of Apollo Server/Client where they are using it in production. There are more that have a hybrid. E.G. old-school REST endpoints and limited Apollo Server while migrating to Client or perhaps only a few micro-services that use it.
The most likely by far is to speak with someone who says they want to use it and either they haven't tried it or someone tried to code it and either it was too much of a challenge or took too much time, etc. Granted, I haven't talked to "every" company in the Bay Area ... so, please take this with a grain of salt.
At my last company (thousands of developers) we had some people talking about it and testing something, but there was nothing in production. It was mostly a Java shop and their Server is not as Shiny as the JS implementation (or so I'm told)

 

Isn't GraphQL tunneled through REST already ?
I think comparing GraphQL and REST as two different technologies is a bit misleading. One can't replace another, because one is simply a higher abstraction transported over another: GraphQL is a Data Oriented Querying language with complete end to end management - but it uses POSTs and GETs through HTTP - it's REST with good tooling on both sides and in between !
It's also important to understand that GraphQL is very powerful as a data tool, but it would be an overkill for pretty much anything else. I've seen people bending it to make it act as an authentication API !

 

There are a few things that are common, but there are a lot of differences as well. There can be a hybrid approach as well, or standalone implementations too. That is why mentioned about things REST can be good for, and GraphQL not being a silver bullet. And totally agreed about the data tooling part, that is what it does best, and only using it as an authentication API would be a poor use of GraphQL.

 

The edge icon/logo in this article is outdated ;)

 

Haha, good eye.

 

GraphQL is one of those things that is shiny and everyone wants to use it, but most of the times it's overkill. I would say only use it for large models, models with dynamic data structures (think MongoDB), or for fetching data from multiple sources (APIs, databases, cache, files, etc.). Otherwise, stick to tried and tested simple REST APIs.

 

Excellent explanation!
Thanks for sharing.

 

Glad that it helped. Thanks for the appreciation.

 
Sloan, the sloth mascot Comment marked as low quality/non-constructive by the community View code of conduct

This post is half-assed, dude.
"The major benefits of GraphQL are :

Let’s take a deeper look at how GraphQL tackles these."

  • did you forget to follow up with a bullet list? Weird grammar everywhere.
 

That's a pretty toxic way of responding to someone else's work. Don't take that as an offense but as a well meant personal advice: If you don't want other people to really hate working with you, change your communication!

BTW @saranshk Thanks for the article! I recently witnessed a pretty emotional argument about the pros and cons of REST and GraphQL and oh boy it could have used some objective insights like the ones you gave, here :)

 

Thanks for the kind words @bkis :)

 
Sloan, the sloth mascot Comment marked as low quality/non-constructive by the community View code of conduct

I was being honest, dude. Look i can see this community having its' place as a lower-quality spin off of medium dev-blogs, but there's gotta be at least a minimal level of due diligence. I cannot appreciate someone writing an article and not even reading it back before posting it... that's why i wrote "half-assed"

Well, dude, thank you for proving my point.

 

Don't know what happened there, but put the bullet list back in there. As for grammar, could you point to instances? I don't see any of those and even Grammarly seems to agree.