Tuesday, 29 October 2019

Introduction to GraphQL


GraphQL is a specification that provides a query language for your API. Using GraphQL client can ask the data that he is interested in.

Who developed GraphQL?
Facebook developed GraphQL and open sourced it.

How traditional APIs works?
In traditional approach, Client request for some data by hitting an endpoint. Server receives the request, process it and send the response to client.


Here the problem come in, Client may not be interested in all the response data he is received from server. Client may be interested in subset of the response. Client will extract/filter the subset the and consume as per the needs.

How the APIs works with GraphQL?
a.   Client send a GraphQL query to server.
b.   GraphQL server send the results back to client, the result contains exactly the payload that client is interested in.


For example, a sample GraphQL query looks like below.
query {
  allUsers {
    id
    name
  }
}

In the above query, client requesting for all the users information using ‘allUsers’ API, and client is interested in only id and name fields of the user.


Response from GraphQL server looks like below.
{
  "data": {
    "allUsers": [
      {
        "id": "1",
        "name": "Ram"
      },
      {
        "id": "2",
        "name": "Rahim"
      },
      {
        "id": "3",
        "name": "Robert"
      },
      {
        "id": "4",
        "name": "Antony"
      },
      {
        "id": "5",
        "name": "Krishna"
      },
      {
        "id": "6",
        "name": "Saurav"
      }
    ]
  }
}


You can even ask for last three users information with below query.
query {
  allUsers (last : 3) {
    id
    name
  }
}

You will get response like below.
{
  "data": {
    "allUsers": [
      {
        "id": "4",
        "name": "Antony"
      },
      {
        "id": "5",
        "name": "Krishna"
      },
      {
        "id": "6",
        "name": "Saurav"
      }
    ]
  }
}

Advantages
a.   Client is given freedom to ask what exactly he need. So no further filtering is required at client end.
b.   You can ask GraphQL server for all the data you require in single request. GraphQL can able to aggregate the responses from multiple APIs.
c.    Many languages like Java, Go, nodejs has implementations of GraphQL Specification.
d.   Since GraphQL is a specification, it is completely language independent, you can write a GraphQL client in Java and you can communicate with a GraphQL server that is written in Go.


Note
a. If you want to play with GraphQL online, try below link.



Previous                                                    Next                                                    Home

No comments:

Post a Comment