Today I Learned - Rocky Kev

TIL GraphQL vs Rest

POSTED ON:

TAGS:

I'm pretty happy overall with my API experiences, especially coming from a world where APIs was rare.

So when I learned about GraphQL a few years ago, I struggled to figure out 'why'?

But this post convinced me of the features. Stop Using REST For APIs

Let’s say, for example, we are displaying a user’s feed with a list of the user’s post and his/her followers.
In our case, we have to display the author of the post, the posts as well as the followers for that user.

If we were to use REST, we would have made at least 2 or 3 requests, similar to this:

/user/<id> to get the User(Author) details likely the name.
/user/<id>/posts to get the list of posts posted by that user.
/user/<id>/followers to get the list of followers for the user.

But in all these cases we are over-fetching the data.
For example, in the first request, we need only the name, but we get all the details about the user when we use this approach.

This is when GraphQL shows it’s power. We need to specify the query and we can get the desired output.

To achieve the same using GraphQL, we can use a query similar to this:

query {
  User(id: '123') {
    name
    posts {
      title
    }
    followers {
      name
    }
  }

Tl;dr - sometimes you need to combine API calls to get the exact data you need. If the API author swapped over to a graphql format, it'll be easier to filter the data you do need.

For a clearer example of it all:

REST APIs

Benefits of REST

Limitations of REST

GraphQL APIS

Benefits of GraphQL

Limitations of GraphQL


Related TILs

Tagged:

TIL Multiple Fetch Requests

I've been frequently dealing with this scenario in the past few weeks. I wanted to make multiple fetch requests, and then merge everything together when it's all done. To make multiple/parallel fetch requests:

TIL how JSON bet on simplicity

I had a goal of being able to put JSON standard on the back of a business card

TIL GraphQL vs Rest