Introduction to GraphQL

What’s GraphQL?

A query language to build & query APIs. Invented by facebook in 2012, to solve its complexity in REST APIs.

It’s a good fit for companies where there’re tons of data we’d need otherwise to access through REST APIs. It’s not a replacement for REST, it’s an alternative for projects with large data sets.

GraphQL vs REST APIs

REST API

underfetching

Let’s say we want to retrieve the posts for a user and then, the comments and likes for a user’s post. In a REST API we’d have the following:

api/users/{id}/posts
api/users/{id}/posts/{postId}/comments
api/users/{id}/posts/{postId}/likes

With a single endpoint we cannot retrieve all the data. We need to call multiple endpoints to have all data we need.

overfetching

Let’s say I want to iterate the PostDescription for one user posts history. If I call the following endpoint it will give to me way more data than I need:

api/users/{id}/posts

gives back:

PostDescription UserId UserImage PostId PostCreationTime PostLocation etc.

This is way more data than I need to iterate and useless to me.

GraphQL

We have one endpoint which handles all these things for getting posts comments and likes. We just need one query to get all results as we specify which data we want back.

endpoint:

/graphql

query:

{
  user(id:1258) {
    username
    userimage
    postdescription
    comments(postId : 3) {
      username
      userimage
      commentdescription
    }
    likes(postId:3) {
      username
      userimage
    }
  }
}

Github’s explorer

LIttle github’s test tool to explore and learn GraphQL.