My Experience with GraphQL

What is GraphQL?

GraphQL is described as ‘a query language for your API’. It was created by Facebook back in 2012 for use in their mobile applications, but was made open source in 2015 and has grown in popularity ever since.

GraphQL is an alternative to REST architecture and allows users to specify the data they would like to receive, rather than a REST endpoint simply returning everything.

An endpoint returning unnecessary data is known as ‘overfetching’ and results in requests which are larger than they need to be, the frontend needing to parse data it won’t use, and potentially a client having to perform multiple network requests until it has all the information it needs.

For example, compare these two queries:

REST Query

GET /users/1
{
  name: "John Doe",
  email: "john@test.com"
  // ...more user information
}

Now if we also wanted to retrieve the comments of this user, we may need to perform another query before we can get all the information we need. Something like:

GET /users/1/comments
{
    {
        title: "I really don't like too many requests"
        body: "REST is great but sometimes makes me have to fetch a lot of data"
    },
    {
        title: "I wonder if there's another way of doing this?"
        body: "Surely this is a problem people have encountered before?"
    }
  // ...more user comments
}

GraphQL Query

In GraphQL, things are much simpler. We can just do:

query {
  User(id: "1") {
    name
    email
    comments {
      title
      body
    }
  }
}

The above would return a single object containing all the information in just one request. It’s far more efficient and we don’t have to receive all the fields that we would otherwise need to discard had we queried a REST endpoint.

Conversely, we don’t underfetch either. This is when an endpoint doesn’t give us enough information so we have to make n additional requests to get hold of everything that we need. For example, we may retrieve a list of 100,000 users but then need to separately request their comments.

This would be an expensive operation (and probably bad design regardless of whether you’re using REST or GraphQL).

GraphQL is a specification

Many people imagine GraphQL to be like an ORM or a replacement database. This is not the case. It’s merely a specification that can be implemented in any language and describes a way to relate to your data. The spec is easy to read and can be checked out here.

Pros of using GraphQL

No Overfetching

As described above, the client does not receive data that it won’t use. Instead we simply request what we need and GraphQL returns the appropriate data. This means that we have smaller payloads, more efficient use of resources, and more flexibility on the frontend.

Modern

This matters more to some people than others, but it’s undeniable that GraphQL is on the ‘cooler’ end of the developer spectrum. It is an interesting technology that has a lot of potential.

In the State of Javascript 2018 survey, GraphQL won the ‘Highest Interest’ category with a staggering 87.7% of developers who have heard about GraphQL wanting to learn it!

Strongly Typed

GraphQL uses a strong type system which maps the API. Everything exposed in the API is contained in the GraphQL schema using a schema definition language. Once the schema is created, there is a single souce of truth for both the backend and the frontend and no need for translation between the two.

This allows for fewer errors, validation at compile-time, and you can be certain of what you are passing to the API and receiving from it.

Flexible

By allowing the client to dictate the data it requires, your frontend can move a lot faster without tying up a great deal of backend resources. This is significantly better than a 1:1 matching of endpoint to request where the frontend needs to normalize a great deal of data in order to present the correct values to the end user.

Cons of GraphQL

It’s New

This isn’t necessarily a bad thing, but the ecosystem is - while growing - less mature than what is available should you choose to go with a standard REST setup.

For many companies choosing the ‘boring’ option makes far more sense. There’s nothing wrong with that! For others, then GraphQL is an exciting new way to do things.

Complex Queries

This is something of a ‘solved’ problem in GraphQL but it can trip people up. For example, what happens if a user (perhaps maliciously) makes a request like this:

query {
  User(id: "1") {
    name
    email
    about
    address
    city
    zip
    country
    comments {
      title
      body
    }
    pictures {
      url
      order
    }
    likes {
      website {
        title
        url
      }
    }
  }
}

This is a bit of a trivial example, but you get the idea. A query can rapidly bloat and consume a lot of server resources. In a REST API you could potentially tweak each endpoint to retrieve its specific data in the most specific way.

In GraphQL you can use tools like DataLoader to handle your requests via batching and caching to reduce the load on your server.

Additionally you can limit the complexity of queries through Query Cost Analysis. There are a few packages which make this easier such as GraphQL-Cost-Analysis which computes the cost of the query and optionally blocks it if over a certain threshold.

Learning Curve

As GraphQL is quite new, it may take you time to get up to speed with it and figure out if its a good fit for you. Also, there are a few ‘gotchas’ that you may be unfamiliar with compared to REST. There are many resources covering these however.

My experience with GraphQL

At BeatGig we’re using GraphQL to power our new API and my experience has been largely very positive. Although it presented a bit of a learning curve, it has allowed for very rapid development and a much quicker integration between the backend and the frontend.

It’s not a silver bullet but when it comes to needing a very flexible way to query and subscribe to our data, it works well for us. There were some initial pains in the setup and understanding exactly how to map our existing functionality to GraphQL but this has gone fairly smoothly so far.

Something that has benefitted us hugely however, is using GraphQL-Yoga, and Prisma which gives us a lot of the CRUD features out of the box, and has pre-configured an express server with Apollo in the case of GraphQL-Yoga.

This allowed us to get up and running very quickly and development has been a very enjoyable experience since!

Conclusion

GraphQL isn’t going to be for everyone, but it’s a very interesting technology that reduces some of the frustrations you may feel (particularly on the frontend) when you’re using REST endpoints.

It has an intial learning curve but allows for rapid development and flexible access to your underlying data. The ecosystem is growing very quickly and a large number of developers are interested in learning it, so that ecosystem should continue to grow.

Overall it’s a useful tool in any developer’s arsenal and definitely worth trying out!

A tech newsletter that teaches you something new

This blog was created to document my own learning, and share useful tips with other software engineers.

My newsletter is like that, but straight to your inbox! It contains useful links I've found around the web, sneak peeks of my new articles, and access to free resources I've created.

Sign Up

You can unsubscribe whenever you'd like, and I probably hate spam even more than you do.