Software Artist’s blog

Keep it simple!

Introduction to GraphQL

“This post is not about how to implement GraphQL APIs and assumes that the reader has prior knowledge of REST and APIs.

We are settled with the REST API since most of the applications started using JSON APIs for communication. Now SOAP API has started becoming obsolete because XML APIs can also be implemented using REST.

Ruby on Rails is famous for its support for REST and REST routes generation. Rails’ implementation of REST is an inspiration for various other web application development frameworks.

Everyone is convinced with the REST standards and it has become a defacto standard for API implementation.

Need of REST alternative

In the last few years, mobile has emerged as a primary platform for accessing applications through mobile apps and mobile browsers. Everyone started implementing REST APIs for mobile applications and backend server communication. The REST APIs for mobile application is working well without much hassle for most of the applications.

Most of the famous web applications have different versions of their application running on a different platform and whenever there is a change in the application UI/UX then frontend team have to make requests to the backend team for implementing specific REST APIs for performing operations. It is unnecessarily repetitive and annoying for the backend team to maintain all those API endpoints.

Consider a case, where we are having a tasks list UI component where we display task name and status. But the API we have for fetching tasks i.e. /tasks fetches all the details of the task along with the name and status. So other data is unnecessary for the task list component which is fetched for the task list UI component.

The same is the case for Create, Update and Delete (we will call it CUD in this post) operations, there can be different requirements of the response parameter when a CUD operation is performed.

This thing is observed by lots of application developers. Also, there was a try to implement a library like json-serializer in Rails, to perform selective fetch but it was not curated for fetching relational i.e. has_many and has_one object attributes selectively.

What is GraphQL?

In 2015, Facebook came up with a solution to the constantly changing API data requirement with GraphQL.

The name GraphQL reminds us of SQL. Well, GraphQL is also a query language. One can ask that, if it is query language then on which console we should be running these GraphQL queries? And is that console constant for CUD operations?

The answer is, GraphQL works on a single POST REST API endpoint which we can call a console for performing CRUD operations. Most of the time it is /graphql.

We perform all the operations only by changing the query in the request body of the POST API. So, for API users there is no need to list out API endpoints for performing the various operations.

GraphQL works on the principle, request the data only which you require.

Suppose, If we are fetching users data then we may need email, subscripiton, status, and name.

query {
  users {
    name
    email
    plan
    status
  }
}

And it returns JSON data as follows.

{
  "users": [
     {
      "name": "Amit Kumar",
      "email": "dummy-1@example.com",
      "plan": "premium",
      "status": "active"
      },
     {
      "name": "Sumit Kaur",
      "email": "dummy-2@example.com",
      "plan": "basic",
      "status": "active"
      },
     {
      "name": "Rahul Patil",
      "email": "dummy-3@example.com",
      "plan": "royale",
      "status": "active"
      }
  ]
}

But there is one other requirement to fetch address instead of status in the same request. Then we can simply change the above query like below and get the data.

query {
  users {
    email
    name
    plan
    address {
      state
      city
      country
    }
  }
}

And it will return JSON data like below.

{
  "users": [
     {
      "name": "Amit Kumar",
      "email": "dummy-1@example.com",
      "plan": "premium",
      "address": {
         "state": "Maharashtra",
         "city": "Nashik",
         "country": "India"
        }
      },
     {
      "name": "Sumit Kaur",
      "email": "dummy-2@example.com",
      "plan": "basic",
      "address": {
         "state": "Punjab",
         "city": "Amritsar",
         "country": "India"
        }
      },
     {
      "name": "Rahul Patel",
      "email": "dummy-3@example.com",
      "plan": "royale",
      "address": {
         "state": "Gujrat",
         "city": "Surat",
         "country": "India"
        }
      },
  ]
}

We didn’t need to request a new API for the new requirement. We just included what we want and excluded what we didn’t want.

For GraphQL mutations where we modify the data, we can also request specific data fields in the response when the modification is done.

mutation CreateSubscriptionForEpisode($id: User!, $subscription: ReviewInput!) {
  createSubscription(idd: $user, subscription: $subscription) {
    start
    end
  }
}

# Variables
{
  "id": 12,
  "subscription": {
    "start": "2022-01-01T01:12:34.901Z",
    "end": "2023-01-01T01:12:34.901Z",
    "plan": "Premium"
  }
}

The mutation query will create a subscription record and return only requested data as below.

{
  "start": "2022-01-01T01:12:34.901Z",
  "end": "2023-01-01T01:12:34.901Z"
}

Here we have requested start and end dates in the response.

Graphql is really being useful for mobile applications for performance and the speed of development.