REST and GraphQL are both standard ways to develop back-end apis. But over the past decade, REST APIs have dominated as an option for developing back-end APIs. And many companies and developers actively use it in their projects.

But REST has some limitations, and there is an alternative – GraphQL. GraphQL is a great choice for developing apis in a large code base.

What is GraphQL?

GraphQL was developed by Facebook in 2012 for internal use and made public in 2015. It’s a query language for the API, and it’s also the run time to complete these queries with your existing data. Many companies use it in production.

The official website describes GraphQL in this way.

GraphQL provides a complete, understandable description of the data in your API, gives customers the ability to ask for exactly what they need, not more, makes the API easier to evolve over time, and enables powerful developer tools.

We’ll see how it all works in this blog post.

REST API issues

  • Querying multiple endpoints
  • Excessive access
  • Insufficient fetch and N +1 request problems
  • Not fast enough to respond to changing customer end requirements
  • High coupling between background controller and front view

So, what are these problems, and how does GraphQL solve them? Well, we’ll learn more in the future. But first we need to make sure you’re comfortable with the basic concepts of GraphQL, such as type systems, schemas, queries, mutations, and so on.

Now let’s look at some examples to better understand the disadvantages of using REST apis.

Super take

Let’s assume that we need to display this user card in the user interface.

With REST, the request will be a GET, at /users/1.

The problem here is that the server returns a fixed data structure, like this.

{
    "_id": "1"."name": "Aagam Vadecha"."username": "aagam"."email": "[email protected]"."currentJobTitle": "Software Engineer"."phone": "9876543210"."intro": "As a software engineer my daily routine revolves around writing cleancode, maintaining infrastructure, and building scalable softwaresystems. In my free time I love to write tech blogs, freelance, listenmusic, and watch thrillers."."website": "https://www.aagam.tech"."gender": "MALE"."city": "Surat"."state": "Gujarat"."country": "India"."display_picture": "8ba58af0-1212-4938-8b4a-t3m9c4371952"."phone_verified": true."email_verified": true."_created_at": "2021-03-08T14:13:41Z"."_updated_at": "2021-03-08T14:13:41Z"."_deleted": false
}
Copy the code

The server returns additional data (besides name, introduction, and job title) that is not needed when the client builds the card — but is still present in the response. This is called overfetching.

Overfetching brings additional data on every request that the client does not need. This increases the size of the payload, which ultimately has an impact on the overall response time of the query.

To make matters worse, the situation escalates when a query fetches data from multiple tables, even though the client doesn’t need the data at the time. So if we can avoid it, we must avoid it

With GraphQL, the query in the request body would look something like this.

It will only return the name, Intro, and currentJobTitle that the client needs, so the over-fetching problem is solved.

Insufficient value and n+1 request problem

Now let’s assume that this UserList needs to be displayed in the user interface.

With REST, given that “experience “is a table with a user_ID foreign key, there are three possible choices

  1. One is to send some precise fixed data structure from all the foreign key linked tables into the user table in the GET/Users request, and many frameworks provide this option.
{
    "_id": "1"."name": "Aagam Vadecha"."username": "aagam"."email": "[email protected]"."currentJobTitle": "Software Engineer"."phone": "9876543210"."intro": "As a software engineer my daily routine revolves around writing cleancode, maintaining infrastructure, and building scalable softwaresystems. In my free time I love to write tech blogs, freelance, listenmusic, and watch thrillers."."website": "https://www.aagam.tech"."gender": "MALE"."city": "Surat"."state": "Gujarat"."country": "India"."display_picture": "8ba58af0-1212-4938-8b4a-t3m9c4371952"."phone_verified": true."email_verified": true."_created_at": "2021-03-08T14:13:41Z"."_updated_at": "2021-03-08T14:13:41Z"."_deleted": false."experience": [{"organizationName": "Bharat Tech Labs"."jobTitle": "Software Engineer"."totalDuration": "1 Year"}]."address": [{"street": "Kulas Light"."suite": "Apt. 556"."city": "Gwenborough"."zipcode": "929983874"."geo": {
                "lat": "9-37315"."lng": "81.1496"}}}]Copy the code

But this approach can produce expensive queries, over-fetch all the other/Users requests, and end up bringing back a lot of data from all the foreign key tables (addresses, experiences) that is not needed in most cases.

For example, if you want to GET user data somewhere else on the front end, you just need to display the user’s website, so you make a GET User /1 request. But it superfetches data from experience tables and address tables that you don’t need.

  1. The second option is that the client can go to the server multiple times like this.
GET /users 
GET users/1/experience
Copy the code

This is an example of underfetching because an endpoint does not have enough data. But multiple network calls can slow down the process and affect the user experience. : (

Also, in this particular case of the list, the underfetch escalates and we run into an N +1 request problem.

You need to make one API call to get all the users, and then make a separate API call for each user to get their experience, something like that.

GET /users 
GET /users/1/experience 
GET /users/2/experience 
...
GET /users/n/experience.
Copy the code

This is known as the n+1 request problem. To solve this problem, we usually do a third option, which we’ll discuss now.

  1. Another option is to create a custom controller on the server that returns a data structure that meets the customer’s requirements at that point in time.
GET /user-experience
Copy the code

This is how the major REST API cases work in the real world.

A simple GraphQL request, on the other hand, works seamlessly on the server side without any development, and it looks something like this.

No overfetching, no underfetching, and no development on the server. This is awesome

Tight coupling between front-end views and back-end apis

Well, you could argue that you could just use REST, make a server controller with one initial development effort, and be happy — right?

However, there is one big drawback to using custom controllers.

We’ve tightly coupled the front view and the back end controller, so overall it takes more effort to cope with client changes. It also gives us less flexibility.

As software engineers, we know how often requirements change. In this case, the custom controller GET/User-Experience returns data based on what the front-end view wants to display (user name and current role). Therefore, when requirements change, we need to refactor the client and server.

For example, after a considerable amount of time, the requirements change and the UI needs to display the user’s last transaction information rather than experience data.

With Rest, we need to make relevant changes at the front layer. Also, in order to return transaction data from the back end rather than experience data, the custom controller either needs to be refactored (data send, routing, etc.) or we need to make a new controller in case we want to keep the old one.

So basically, changes in customer requirements greatly affect what the server returns — which means we have tight coupling between the front end and the back end

It’s better not to make any changes on the server, just on the front end.

With GraphQL, we don’t need to make any changes on the server side. Front-end query changes will be minimal, like this.

No server API refactoring, deployment, testing – this means time and effort saved

conclusion

I hope you can see from this article that GraphQL has many advantages over REST in many ways.

It may take more time to set up GraphQL initially, but there are a number of scaffolding to make the job easier. Even if it takes more time in the beginning, it will give you a long-term advantage and be totally worth it.

Thanks for reading! I hope you enjoy this article and that it gives you more insight into your next choice. If you need some help, feel free to connect with me on LinkedIn.


Aagam Vadecha

Read more from this author.


If this article is helpful to you, please send it to me.

FreeCodeCamp’s open source courses have helped over 40,000 people land developer jobs. Let’s start