GraphQL - my learnings in progress

·

2 min read

GraphQL is a query language - we can think of SQL ( getting data, mutating data ) over HTTP.

With REST API as well, we have the capabilities to query for data or mutate data.

GraphQL is an alternative to REST API.

It comes into the picture when the data scale of the app grows.

Drawbacks with REST API:

  1. Overfetching: getting more data than we need ( website.com/api/courses ). We might just need some specific data from the courses object and not all, to display on a webpage.

  2. Underfetching: getting less data than we need. Sometimes additional requests need to be sent to get more data that we want to display on a page.

Single endpoint:

graphqlsite.com/graphql

Not like rest API, where for each resource, you have an endpoint.

Query {
 courses {
   id,
   title,
   thumbnail_url
 }
}

Suppose we want to fetch more information, to avoid underfetching, we can specify exactly what we need in a single request like the below:

Query{
  course(id:"1"){
   id,
   title,
   thumbnail_url,
   author{
    name,
    id,
    courses{
     id,
     title,
     thumbnail_url
     }
    }
 }
}

Nesting the properties inside the query itself.

A graph allows us to create relationships between nodes or in terms of objects/entities in the real world. For example, in the below image, we have 3 objects: games, authors, and reviews. Using GraphQL, we can create a relationship between all three entities and fetch them in one go, based on what we need. That sample query is shown in the below image. We want to retrieve a game with id=2 and the attributes of the game in which we are interested are the title and review of the game. And within review, I am interested only in rating and author. And within the author, I am interested only in the name.

One thing to note is that, actually these entities are linked to each other, but they are not stored as nested attributes in the backend. All 3 are different resources, but, we are getting them back in a single query. In the world of REST API, we would have to send multiple requests to fetch this kind of related data.

courtesy: netninja