GraphQL vs REST

Understanding the pros and cons of adopting GraphQL vs REST for your API.

GraphQL vs REST

Until recently, it was extremely likely that the APIs you designed and consumed were REST APIs. Now, the landscape has changed, and popular services such as GitHub, Facebook, Pinterest, and even Starbucks are using GraphQL. As a developer, you may be faced with designing an API at work and have the choice of implementing a REST or GraphQL service. But how do you choose?

Both have their advantages and disadvantages, so it is essential to understand these when deciding what technology to use.

REST

REST is an acronym for ‘Representational State Transfer.’ It is a stateless and uniform format that decouples the client from the server.

REST is initially fairly simple to implement and uses the HTTP transport layer to support creating, reading, updating, and deleting data (CRUD).

Each operation in REST is characterized via an endpoint. For example, you may want to retrieve a user from your API, and you might have an endpoint like this:

/api/users/1

This tells the server that you are requesting the user resource and want to select the user with the identifier 1.

In principle, this is pretty straightforward and very easy to reason with. You may, however, be able to see where issues can arise.

Dealing with multiple requests

With a system of any complexity, you need to make multiple requests to get the data you need.

For example, let’s say you have a user, and the user has photos. You have two ways to approach this as a developer:

  1. Add the photos to the response for the api/users/ endpoint
  2. Add a separate endpoint, api/users/:id/photos

Both approaches will work, but which is best?

In the first option, you will end up needing to send and consume far more data than you need for every user request.

In the second option, you will need to make another call to get their photos once you have retrieved your user.

This is a simplified example, and there are clever ways to try and reduce this issue, such as only calling the endpoint when a specific resource is required. But this complicates the job of the front-end developer. In short, the major issue in REST is the requirement to have multiple endpoints. This ends up becoming hard to reason with and difficult for your engineering team to maintain.

GraphQL

GraphQL offers many advantages over REST, especially because it removes the multiple endpoints issue. Instead, graphQL has a single endpoint which allows you to declaratively tell the API what you want.

Using our previous example of retrieving a user and their photos above, we would simply do the following in GraphQL:

query {
  user {
   name
   photos {
     id
     path
    }
  }
}

Now, in a single request, we have retrieved our user and their photos. But what else do you notice?

We have only retrieved one field from the user. We do not need their ID, their email, or any other information, so we do not ask for it.

This results in a much smaller payload and returns exactly what we need. Nothing more, nothing less.

Don’t worry if this looks a bit confusing right now. In the next few lessons, we will learn how a GraphQL schema is structured and how to work with it.

With all that said, GraphQL is no silver bullet and introduces its own complexity and issues. We will explore some of these and how to mitigate them in a further lesson.

So which should I choose?

This really depends on your use case. Neither REST nor GraphQL are better than one another. They simply work differently.

If you are concerned about retrieving exactly the data you require and want a more declarative way to consume your API then I would recommend adopting GraphQL.

If you are happy making multiple trips to retrieve data and are conscious of the tradeoffs of designing endpoints to meet specific use cases, then stick with REST.

One of the advantages of GraphQL is that you can adopt it incrementally or even use it as a wrapper over a REST API. This does not need to be a final decision, but it is worth exploring the pros and cons of each.

A good API is created the most through considered design and less through the specific technology stack. But if you are interested in GraphQL and want to learn more, then read on!

The code below demonstrates a simple GraphQL schema with a User type and a Photos type. We then add a resolver, which allows you to return data for both of these types.

var { graphql, buildSchema } = require('graphql');
// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
  type Query {
    user: User
  }

 type Photos {
    id: String
    path: String
  }

  type User {
    id: String
    name: String
    email: String
    photos: [Photos]
  }

 
`);

// The root provides a resolver function for each API endpoint
var root = {
  user: () => {
    return {
      id: 3232324,
      name: 'John Doe',
      email: 'john.doe@example.com',
      photos: [{
        id: 123,
        path: '/img/path/here'
      }]
    }
  },
  photos: () => {
    return {
      id: 123,
      path: '/img/path/here'
    }
  }
};

// Run the GraphQL query '{ user  {...} }' and print out the response
graphql(schema, '{ user { id, name, email, photos {id, path }} }', root).then((response) => {
  console.log(response);
});
Example of a simple GraphQL Schema