DEV Community

Cover image for REST vs GraphQL
Matheus Lima
Matheus Lima

Posted on

REST vs GraphQL

REST and GraphQL are technologies used to consume APIS. However, each one has their own particularity. This text aims to compare each one of them and provide a short introduction to GraphQL.

GraphQL
It is a query language for API, according to your specification. It was developed by Facebook Team to fix problems found in the REST API.

The principles of GraphQL are:

  • You receive what you ask for.

Data is returned from the same fields that you request by the GraphQL query, for example:

Query example:

query {
  city{
    name
  }
}
Enter fullscreen mode Exit fullscreen mode

Query return:

{
  "data": {
    "city": [
      {
        "name": "jundiaí"
      },
      {
        "name": "campinas"
      }
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

Data is returned from the same fields that you request by the GraphQL query, for example:

const data = {
    city: [
      { id: '1', name: 'jundiaí', state: 'SP' },
      { id: '2', name: 'campinas', state: 'SP' },
    ],
  }
Enter fullscreen mode Exit fullscreen mode

The objects have the fields "state" and "id", but if we don't request them in our query, the API will not return them

  • You need only one request.

Unlike REST where we need to request with numerous endpoints, in GraphQL only have to do one request.

REST vs GraphQL

Over-fetching: it's very common to request using the REST API and getting too much unnecessary data and fields returned to us. As we saw, this doesn't happen with a GraphQL query.

Under-fetching: we can request from the REST API, but your response may not return the data you need, and because of that, another request to a different endpoint must be made.

Finally, GraphQL has one endpoint. This is a big advantage because REST uses too many endpoints which may be confusing.

Top comments (0)