Why GraphQL is the Future of APIs
Since the beginning of the web, developing APIs has been a difficult task for developers. The way we develop our APIs must evolve with time so that we can always build good, intuitive and well-designed APIs.
In the last few years, GraphQL has been growing in popularity among developers, and a lot of companies have started adopting this technology to build their APIs. GraphQL is a query language developed by Facebook in 2012 and released publicly in 2015. It has been gaining a lot of traction and been adopted by a lot of big companies such as Spotify, Facebook, GitHub, NYTimes, Netflix, Walmart, and so on.
In this series of tutorials, we're going to examine GraphQL, understand what it is, and see what features make this query language so intuitive and easy to use.
So, let's get started by examining the problems with REST, and how GraphQL solves them. We will also find out why companies have been building their APIs with GraphQL, and why it is the future of APIs.
A long time ago, when we changed our API design from SOAP to REST, we thought that move would give developers more flexibility in their work. We can't deny that it worked pretty well for some time and was a good move at the time. As the applications and the web have been getting more and more sophisticated, the APIs naturally evolved as well, following these changes.
However, REST does have a lot of problems. Let's see what they are:
A lot of endpoints
Each resource in REST is represented by an endpoint. So, in a real-world application we would end up having a lot of endpoints for a lot of resources. If you want to make a GET request, you would need an endpoint specific to that request, with specific parameters. If you want to make a POST request, you would need another endpoint just for that request.
But, what's the problem with that? Let's imagine we are building a huge social media application like Facebook. We will end up with a lot of endpoints which means more developer time is going to be spent developing and maintaining these APIs.
Over-fetching and under-fetching of information
A real problem that annoys a lot of developers is over-fetching and under-fetching information through REST APIs. This is because REST APIs always return a fixed structure. We can't get exactly the data that we want unless we create a specific endpoint for that.
So, if we need only a tiny piece of data, we have to work with the whole object. For example, if we only need to get the
age of a user in a REST API, there's no way we can get exactly this data without fetching the whole object.
There's also a problem with under-fetching of information. If we want to get data from two different resources, we need to make different calls to two different endpoints. In a huge application, this doesn't scale so well since there will be cases where we only need to get a specific piece of data, not the entire object. Now, imagine we're building an application that's going to have 100 endpoints. Imagine the amount of work and code that we need to write. This will become more difficult with time. The code also gets hard to maintain and developers feel lost in the process.
One of the painful points in REST, in my opinion, is versioning. With REST APIs, it is very common to see a lot of APIs with v1 or v2, but in GraphQL there's no need for it since you can evolve your APIs by adding new types or removing old ones.
In GraphQL, all you need to do to evolve your API is to write new code. You can write new types, queries, and mutations without the need to ship another version of your API.
So, you won't see GraphQL APIs with endpoints like the following:
Why GraphQL is the future
Back in 2012, Facebook faced a problem while they were developing their mobile applications which led them to create GraphQL. Those problems are very common, especially when we're talking about RESTful API design. As discussed these problems are:
- Poor performance
- A lot of endpoints
- Over-fetching or under-fetching of data
- Shipping another version every time we need to include or remove something
- Difficulty understanding APIs
With a lot of concepts in mind, developers from Facebook developed a better way to design APIs, and later named it GraphQL. Basically, it's the replacement for REST, with a lot of improvements.
With GraphQL, we get a lot of new features that give you superpowers when you are building your APIs. Let's examine them one by one:
There's no need to build a lot of endpoints! With GraphQL, we only get one endpoint, and with that we can get as much data as we want in a single request. Basically, GraphQL wraps all of your queries, mutations, and subscriptions in one endpoint and makes it available to you. It improves your development cycle because you don't need to make two requests to get data from two different resources. Also, imagine that we're building a huge application, we won't get a lot of endpoints and a ton of code as with REST. We will get a single endpoint, and with that endpoint we can make as many requests as we want.
Also, as I said above, an "endpoint-only" approach makes your API self-documented since there's no need for you to build documentation because your developers already know how to use it. They can understand the API just by looking at the code, or by looking at the playground. We're going to learn more about it later on (next tutorial in this series). Seems magical, but it is just GraphQL!
With GraphQL you fetch only the data you need
No more over-fetching or under-fetching of information. You fetch only the data that you need. Remember the poor performance issues that we discussed initially? We don't have that anymore since GraphQL improves the performance of your API, especially in case of slow network connection.
GraphQL makes it easy to start building APIs and be consistent
A lot of people think that GraphQL is pretty complicated because it involves a schema and a single endpoint. Once you start developing APIs with it, you discover that it's easier than you thought. An "endpoint-only" API helps a lot when you're developing your website/app. It makes your API more self-documented and there's no need for you to write a lot of documentation about it.
GraphQL Is The Future
The fact that GraphQL is an open source query language means that the community can contribute to it and make improvements to it. When Facebook released it to the community, it gained a lot of traction and approval from developers. Now, GraphQL has been growing rapidly as more and more developers are starting to build APIs with it. However, some people have been asking if this is really going to replace REST or become the new way to build APIs for real-world applications.
At first, I thought that GraphQL was only hype and just another way to create APIs. However, when I started to study it, I found out that GraphQL has the essential features that are required to create modern APIs for modern applications because it really plays well with modern stacks.
So if I could say something to you now is: yes, GraphQL is really the future of APIs. That's why big companies are betting on it.
In November 2018, GraphQL created a GraphQL Foundation, in partnership with the Linux Foundation, which means that this query language is encouraging its developers to build more documentation, tools, and support for the language. This foundation will ensure a stable, neutral, and sustainable future for GraphQL. So, this is another reason to consider GraphQL to be the future of APIs.
Of course, it won't replace REST immediately because many apps still use it and it's impossible to rewrite them overnight. As more and more companies adopt GraphQL, both UX and DX will improve.
GraphQL is really the future of APIs and we need to learn more about it. That's why I decided to create a series of 4 tutorials that will show how we can work with the best of GraphQL, starting from Queries and Mutations, then Subscriptions, and Authentication.
In the next tutorial of this series, I'm going to dive deep into GraphQL, show how GraphQL works with types, and create our first Queries and Mutations.
So, stay tuned and see you in the next tutorial!
3.4K+ developers have started their personal blogs on Hashnode in the last one month.
Write in Markdown · Publish articles on custom domain · Gain readership on day zero · Automatic GitHub backup and more
That's a good article! Well, like any other technologies out there, GraphQL has downsides too. At-least from what I've experienced while building one.
Now, time for perspectives.
From the Frontend developer standpoint: I love GraphQL as a Frontend Developer. There's nothing like it, Period. So far with every frontend dev I've interacted with, either loves GraphQL or isn't aware of it. There is no in between. Why? First, underfetching irritates client developers. And, when the backend dev asks them to make one more API call to get the required data/state, they almost curse that backend dev. Second, API docs. We all have been there.
From the Backend developer standpoint: The amount of bloatware that it ends up in the Controller layer is just ridiculous. If you use NodeJS(JS) + MongoDB, you wouldn't feel much (loosely typed + json) but if you use strictly-typed languages like Java, it would be an ocean of bloated classes. And upon that, if you use MySQL database, god save you. You'd have to follow any of the GraphQL design pattern and stick to it carefully.
Introducing either Access Management or showing fields based on Persona forces us to do a redefine things in Controller layer. The access definitions which you build in the business logic layer will have to be replicated in the form of Fragments in GraphQL. It can be done but..
In the verge of writing a generic code to provide hassle-free endpoints, we end-up compromising particular API based DB/Cache Query optimisations. Particularly in SQL-based DBs, The indication for invoking a procedure/view over a generalised Prepared Query statement is blurred out, again, unless you follow the design.
From the REST Performance standpoint, HTTP/3 - Quic is coming up. Network bandwidth allocation from the Browser Client to a target happens only once even though you make 10s of request to the same target. So it removes a greater amount of overhead.
Let's suppose, GraphQL comes up with provisions for all the above scenarios, yet we might find it difficult for Enterprises adopting GraphQL as their primary backend API interface. And Why is that? because the innovation in the Web ecosystem is very rapid. That's not the problem. It's the deprecation of the same innovation happens very rapid too -- And Backend ecosystem is not used to this because it prefers stability even its legacy. That's probably one of the reasons why Java is still active in the market.
And if you say Facebook or Github uses it -- they needed an easy interface for their developer API integrations. Infact, Github mentions it in one of their posts. All the other adopters so far, use it for the same purpose. Ease of Integration.
I can go on like this but its not that I want to bi*ch about GraphQL or I'm taking support for REST over GraphQL. The point I'm trying to make is -- GraphQL is a really solid concept and it overcomes the problems that exist in REST by costing to something else, probably because its in an infant stage. Too many REST endpoints aren't manageable either. I hope it evolves to a greater extent so that it blurs out a markup between Web client and backend API layer.
Please correct me in case I've pointed out something wrong, I'd be happy to discuss. Cheers!
Co-founder Moesif.com (API analytics). Previous Microsoft & Zynga. CS from MIT.
We here at moesif, an API analytics company, are seeing a sharp uptake of GraphQL APIs.
Although, right tool for the right job still applies. GraphQL works better in some situations, RESTful works better in others.
The posts, like this one, usually created by good middle developers, but not seniors. This is why.
All pros and cons what you mentioned here are about two extremes.
Nobody uses pure REST API nowadays. You always can create mixed endpoints, with serializers, to get or post any data with any fields you need.
At the same time, it's too complicated to use GraphQL in small or medium projects and support all of these query abilities. Which is not optimized in most cases, because this is the payment for the universal endpoint.
GraphQL was invented on Facebook as a response to its growing departments and amount of developers. It was easier for them to provide the Query sublanguage than every second day making changes in many endpoints.
But we aren't Facebook or Netflix. We don't work in a company with thousands of developers. And we don't need this GraphQL just because this is the next popular hype.
Senior developers must bear this in mind when they choose a stack of technologies.
I grow so weary seeing these paeans to GraphQL claiming it is some kind of panacea and that REST is yesterdays news. Why? Why? Because they gloss over the fact that REST and GraphQL are really best for different use-cases.
So these "GraphQL is the future!" are tiring and tedious. Use the right tool for the job.
It makes me wonder if the authors of these types of posts actually understand REST, its history and what it was designed for or if they really only speaking from their own limited experience of having tried to write clients for both of them and found one easier to work with? That is a lot like blind men arguing over the nature of an elephant.
But since I don't want to be critical of someone I've never met and only read one article from, let me instead suggest they study more about REST before proliferating untruths unintentionally:
Saying "GraphQL is better than REST" is like saying an SUV is better than a bullet train simply because you get to control the SUV and you can go more places with an SUV than a bullet train. Though the latter parts of that statement would be correct the assertion that that makes an SUV "better" completely ignore the benefits of the bullet train and the respective trade-offs of choosing an SUV.
Absolutely, an SUV has its use-cases where it is better than a bullet train. But where a bullet train shines, an SUV cannot compete.
GraphQL use is highly coupled between client and server and when building bespoke mobile apps that is an acceptable tradeoff given its benefits. This is fine if your API is proprietary and/or don't expect your API to live more than a few years. Then you can gain the benefits of smaller and more exact payloads.
But REST, with its hypermedia constraint in tact, was designed to be robust and workable over decades. It was designed to decouple the client from the server as much as possible, and allow clients to interact with servers without having the client developer coordinate with the server developer, or coordinate as little as possible.
So to say the GraphQL replaces the need for REST is a gross misunderstanding of why REST is here to stay. After all, REST was merely a codification of the architecture of the web after the fact, albeit REST APIs need to adhere to more constraint than the we at large.
For those of you who read the post I am commenting on, or similar posts, and are tempted to think "Wow, REST is stupid and GraphQL is a panacea!" do yourself a favor and read these articles which provide a more balanced view of REST vs. GraphQL:
It is safe to use GraphQL for internal use cases, like your internal apps or parts of a bigger picture. You expose your data only to “trusted” developers. But to expose your critical data and DB schemes outside can be dangerous, ideas can be easily stolen.