GraphQL vs REST for API development

REST has been standard when it came to designing APIs. It has its own advantages such as REST revolves around a defined resource and operations that can be performed on that particular resource. However, REST has its limitations and uses cases like anything else out there. For example, when grown, it becomes quite inflexible to adapt to the changing needs of the frontend.

Disclaimer: There is “no size fit all” when it comes to ReST or GraphQL, this article only enables readers to make informed choices

With FAT frontend and SPA’s, a page may need to make several requests to represent a single component to the client. REST’s nested resource also makes it difficult and cumbersome to query backend with multiple HTTP requests

GraphQL is an open-source data query and manipulation language for APIs, and a runtime for fulfilling queries with existing data — Source Wikipedia

GraphQL was developed to cater to the need for more flexibility in interaction with backend. GraphQL’s strongly typed schema also adds more transparency to what is expected from backend at the same time giving the flexibility to change the schema to get desired and exact results from the backend

To illustrate when and where GraphQL can be leveraged over REST, let’s consider a simple example. In a CMS application, we need to display a zone with 50 associated content and users associated with content

RESTful architecture revolves around a resource, but GraphQL revolves around the Schema Definition or data

Data Fetching

In REST, we would typically have to implement multiple endpoints surrounding respective resources. Some may argue that we can use nested resources, correct; but still, we have to make multiple calls to extract data. REST allows nested resources but that still means implementing required HTTP verb actions for that resource as required

In the example above, We need to make at least three calls get data for our page, GET: /zones/:id to fetch zone resource; GET: /zones/:id/contents to get associated contents and multiple calls per content to GET: /content/:id/users to get associated users.

Restful representation

Again details depend on the implementation, we could supply users as part of the content object, but that is again not the point. What we are discussing is that we, in certain circumstances; need to have multiple trips to the server.

GraphQL

In contrast; In GraphQL, one can simply send a query to GraphQL server to get data as needed in the required format. In addition, GraphQL also allows us to restrict the right amount of data required and the format in which it is required using Schema. Here is a regular unintelligent GraphQL query looks like

query {
  User( id: "tre13hd6nuy" ){
    name
    login
    posts {
      name
    }
    followers(last: 3){
      name
    }
  }
}

In GraphQL query above, we are instructing GraphQL server to get a user, supply only name login , all the related posts with name and latest 3 followers of the user in question

{
  "data" {
    "user": {
      "name": "Pankaj",
      "posts": [
        {
          "title": "How to use GraphQL",
        },
        {
          "title": "GraphQL vs REST",
        }
      ],
      "followers": [
        { "name": "Nivedan" },
        { "name": "Shyam" },
        { "name": "Ankita" }
      ]
    }
  }
}

So using GraphQL, we get exactly what and how many we requested.

So GraphQL may not be a magic pill to all your API woes, but it does fit perfectly in some scenarios. Few places where GraphQL can excel RESTful architecture are:

No more over-fetching and under-fetching

One can describe the major benefit of GraphQL with the fact that clients can retrieve exactly the data they need from the API. Clients do not need to rely on multiple REST endpoints for a single resource. Instead, the client can dictate the shape of the response objects to be returned by the backend API.

This solves major issues one commonly encounter with REST APIs, over-fetching and under-fetching of data.

Overfetching means the client is retrieving data that is actually not needed at the moment when it’s being fetched. It thus drains performance (data take longer to download and parse) of the client. Take our CMS scenario in consideration. When fetching zone, we only needed name and slug of that zone, but REST endpoint maybe sending other unnecessary data as well. In contrast, that is not the case with GraphQL

Underfetching is the opposite of over fetching and means that not all required data is included in an API response. This means the client needs to make additional API requests to satisfy its current data requirements.

Taking our CMS scenario into consideration, since we did not get associated content with its associated users in the request for Zone resource. We needed to make several trips to the server to acquire the required data. This may result in N+1 request problem. Meaning that no endpoint can satisfy data requirement for client in one go and client is forced to connect to another endpoint for missing data.

Benefits of a Schema Definition Language

GraphQL uses a strong schema type system to define the capabilities of an API. All the types that are exposed in an API are written down in a schema using the GraphQL’s Schema Definition Language (SDL). This schema serves as the contract between the client and the server to define how a client can access the data.

Once the schema is defined, the teams working on frontend and backends can do their work without further communication since they both are aware of the definite structure of the data that’s sent over the network.

Frontend teams can easily test their applications by mocking the required data structures. Once the server is ready, the switch can be flipped for the client apps to load the data from the actual API.


About The Author

I am Pankaj Baagwan, a System Design Architect. A Computer Scientist by heart, process enthusiast, and open source author/contributor/writer. Advocates Karma. Love working with cutting edge, fascinating, open source technologies.

  • To consult Pankaj Bagwan on System Design, Cyber Security and Application Development, SEO and SMO, please reach out at me[at]bagwanpankaj[dot]com

  • For promotion/advertisement of your services and products on this blog, please reach out at me[at]bagwanpankaj[dot]com

Stay tuned <3. Signing off for RAAM