graphql vs rest

When you upload your vacation photos to Instagram, there’s a built-in option to simultaneously post to Twitter, Tumblr, and Facebook. This modern digital experience is powered by APIs (application programming interfaces), the gateways that allow the backends of multiple apps and services to communicate with one another.

Survival in the larger API economy depends on your ability to design an easy-to-use API that other developers can tap to get the information and resources they need from your service to augment their own products.

For a long time, REST was the de facto way to design APIs. Then in 2015, Facebook open-sourced GraphQL and marketed it as a hot new alternative to REST. Is GraphQL really better, or should you stick to good old-fashioned REST? Let’s explore the key similarities and differences between the two.

What Is REST?

REST is short for REpresentational State Transfer. It’s an architectural style for facilitating communication between computer systems across a network. The central idea behind REST is to design a uniform interface between components. Roy T. Fielding’s original PhD dissertation, in which REST was first formally described, identifies four key constraints of this uniform interface:

  • Resource identification in requests. Any piece of info that can be named is a resource. Resources can be identified through the URI, which is agnostic to the type of resource.
  • Resource manipulation through representations. Instead of directly manipulating the resources, representations of those resources are passed throughout the system. HTML, XML, SVG, JSON, and PNG are examples of resource representation formats.
  • Self-descriptive messages. Each client request and server response contains all the context needed to act on a resource.
  • HATEOAS. Hypermedia As the Engine of Application State is a fancy way of saying that you can dynamically navigate a network of resources via links. Basically every response describes how the API can be used, by providing the URIs for allowable actions within each response. Somewhat controversially, many APIs that call themselves RESTful skip this requirement. But to be truly RESTful per the original dissertation, HATEOAS is a hard requirement.

In practice, most developers focus on the concept of having resources that can be retrieved by sending GET requests to URLs and receiving representations such as JSON in response:

GET /students/1    // response below:    {     “student”: {           “id”: “as5fa7dfa103”           “name”: “John Doe”,           “major”: “Computer Science”            // … more fields here  }

Notice how you will always get all the fields under students in your response, even if your view only cared about the student’s name field. Need related data on a particular student, such as their last post to the school message board? You’ll need to query another endpoint (e.g. GET /students/<id>/posts).

The key thing to notice before we discuss GraphQL in the next section is that in conventional RESTful APIs, the identity and the method of retrieval of a data item are tightly coupled. The endpoint is also the identification of the resource you’re calling. This is how you end up dealing with round trips to multiple rigid endpoints.

WHAT IS GRAPHQL?

GraphQL is a powerful query language specification for designing modern APIs. Let’s take a look at the core features that make GraphQL unique:

  • It’s a server-side runtime. GraphQL makes it easier to retrieve data, by replacing the collection of endpoints for specific resource requests with a single endpoint that can handle multiple resource requests. Data is stored as graphs.
  • It’s a declarative client request language. Front-end developers now have a standardized language for requesting specific data from a single server-agnostic endpoint. Express exactly what your API needs, and get a custom response.
  • It introduces a type system. Strongly typed schemata ensure that when you retrieve specific data from a graph you get exactly what you asked for—no more and no less.

The biggest difference from traditional REST APIs? You can retrieve arbitrary complex data structures from the domain model as a graph. You supply a graph (the query):

query {     Student(id: “as5fa7dfa103”) {        name        posts {           title        }       followers (first: 2) {          name       }     }  }

And receive a graph (which is a subset of application data graph according to the query):

{
    “data”: {
       “User”: {
           “name”: “John Doe”,
           “posts”: [
              { title: “Hello World” }
           ],
           “followers”: [
              { name: “Bob Thompson” },
              { name: “Jane Doe” },
           ],
          }
       }
 }

Notice how the response mirrors the nested graph structure of the original query? That’s the magic of GraphQL.

GraphQL decouples data identity from method of retrieval. Resources are identified by types, and their relationships are captured by schemata. There is only one endpoint you need to speak to, and you can use types to pick and choose which data fields you wish to express in your view.

Should I Use GraphQL or REST for My Project?

At the end of the day, GraphQL is a query language specification and REST is an architectural style. In many ways, GraphQL builds off a lot of the concepts already pioneered by REST.

That said, while it’s tempting to dismiss GraphQL as another tool in a long list of tools for designing APIs, the language specification does introduce some radically new concepts for how a modern API should be designed. The improvements to programmer productivity, especially on the front end, are significant enough that the real question is when not to use it.

Since the GraphQL ecosystem is still relatively new, it’s important to point out the challenges at the time of this writing:

  • Cacheability: It’s inherently easier to cache REST requests because each resource has a URI. Since each request can be different in GraphQL, caching is more complex.
  • Managing query complexity: Just because the server has been decoupled from the client doesn’t mean front-end developers can do whatever they want on the client side. A server still has to do the heavy lifting to handle complex, nested requests. To prevent third parties from requesting too many fields at once, you need to also work out maximum query depths, complexity weighting, and other mechanisms to prevent inefficient requests.
  • Rate limits: Want to limit the number of requests a third-party API can make to your servers? In REST it’s as simple as providing a maximum number of requests per day. In GraphQL, you can’t just treat every return trip to the server as equal. Complex queries lead to more complex rate-limiting calculations.

To be fair, GraphQL has an active community working on all these issues, so only time will tell whether REST will eventually have to RIP. For now, it’s better to take a pragmatic approach when deciding between these two API design paradigms.

In the era of microservices, it’s entirely possible to use both for your project. Use GraphQL for developer friendliness and productivity when possible. In areas where support is weak (e.g. caching), stick to REST.

Read more: No PhD in Data Science? No Worries — It Just Got a Whole Lot Easier