GraphQL

GraphQL

GraphQL is a query language for APIs built and maintained by Facebook.

What is GraphQL?

Let's first break the term "GraphQL" into "Graph" which means queries are now able to crawl into the rest API and pick up the selective information from it, and "QL" which simply means Query Langauge.

Unlike rest API, graphQL provides only one endpoint, out of which based on your requirement resolves the query. In the rest API, the items which we will get as a response are fixed for different scenarios, but in the case of GraphQL, we can ask for what specific field we need.

For Example:

Let's say we have an API to get the card details, so all the fields like "id", "name", "provider" and many more will be fetched, but the user is only asking for the "id", so in that case, rest API is giving extra data which is not required, but with GraphQL it will fetch only the required data which is "id".

Should we replace Rest with GraphQL?

No, not at all, right now most of the applications do not need GraphQL, they are working well with the REST API, and there is no point to implement another resource just to implement GraphQL. Like until unless you are hitting a million queries every single day, you should not switch to GraphQL, usually, that's not the case, as most of them are small applications.

If your application is big enough then you always have the resources to implement GraphQL. But it won't make any difference unless you have a large user base like Facebook, for them it will make that's why they came up with GraphQL.

Syntax of GraphQL

query

query {
  characters(page: 2, filter: { name: "rick" }) {
    results {
      id
      name
    }
  }
}

response

{
  "data": {
    "characters": {
      "results": [
        {
          "id": "291",
          "name": "Rick J-22"
        },
        {
          "id": "292",
          "name": "Rick K-22"
        },
        {
          "id": "293",
          "name": "Rick Sanchez"
        },
        {
          "id": "294",
          "name": "Ricktiminus Sancheziminius"
        }
      ]
    }
  }
}

Here, we only requested the id and name of all the characters., and that's what GraphQL gave us.

Types of model

1. query

The query is used when we need to read or request data from the database.

2. mutation

The mutation is used when we need to perform a CUD(Create, Update, Delete) operation.

3. subscription

The subscription is used when need to enable the web socket feature.

For more in-depth details, refer there official website graphql.org