What are the benefits of using GraphQL?

There are three main benefits of using GraphQL:

  • Ask the server only for what you need, and get exactly that from the database
  • Many resources, one request
  • Typed data

Ask the server what you need, and get exactly that from the database

This means your queries can look like this:

{
  user {
    id
    name
  }
}

and the response from the GraphQL server will be:

{
  "user": {
    "id": 1,
    "name": "Max"
  }
}

Many resources, one request

While a typical application relying on a RESTful backend would require multiple trips to different URLs to fetch all the data your frontend needs to display, GraphQL sends you the data in one trip.

While most examples you'll see of GraphQL typically involve fetching one or two fields on a single model, such as a User's name, this feature is incredibly useful in real-world cases such as this:

{
  user {
    id
    name
    transactions {
        id
        description
        transactedWithUser { 
            id
            name
        }
    }
    paymentDetails {
        id
        name
    }
    subscription { 
        status
        validUntil
    }

  }
}

If that query were to be fulfilled by a RESTful API, it would require:

  • Fetching the User ID, sending it back to the Client

  • Fetching the list of Transactions for that User ID, sending it back to the Client

    • For each transaction, fetching the Transaction's transactedWithUser ID and name, and sending it back to the client
  • Fetching the payment details for that User ID, sending it back to the Client

  • Fetching the subscription details for that User ID, sending it back to the client

You can see how quickly that series of requests can add up to serious waiting time for your end user - especially for slow mobile network connections.

If that query were to be fulfilled by GraphQL, on the other hand, it would require a single request, which would return two objects: a list of errors, and the results object (Typically you would see an empty list of errors, and a full results object, however should your GraphQL server fail to resolve a field, it would still send back any data it managed to resolve).

Typed data

Rather than splitting up your RESTful API by endpoint, GraphQL is organised by Types and Fields. This allows it to provide clear and useful error messages when Clients ask for things that aren't possible. On top of this, Apps can rely on types to avoid having to write code to manually parse inputs (i.e: is this input an object or a string?)