GraphQL vs REST API

GraphQL says,

"Hey, you have one chance at shooting this shot. You can only call my phone once. So when will it be?"

However, REST API says,

"Baby, you can call me as many times as you want. I don't bite."

Say, for example, you want to fetch a user name, age and skin color:

The request, and JSON response, simultaneously, for a REST API will be:

Name

GET  /api/user?id=4
{
"id": 4,
"name":  "Tomisin Lalude"
}

Age

GET /api/age?user_id=4
{
"id": 4,
"age": 23
}

Skin color

GET /api/skin_color?user_id=4
{
"id": 4,
"skin_color": "Brown Skin"
}

while a GraphQL API's will be:

POST /graphql
query {
user(id : 4) {
id
name
age
skin_color
}
}

Do you see it?

  • For REST, you need to call the API three times at different URLs to get those data but in GraphQL, you query a single endpoint.

  • In GraphQL you are POSTing a query as opposed to making a GET request in REST.

  • GraphQL allows you to use nested JSON objects to fetch data as you will observe from the code snippet above. This is the syntax for a GraphQL query.

Let me show you the raw form of the HTTP response body for these two kinds of API.

GraphQL

{
"query":  `
   query {
   user (id : 4) {
   id
   name
   age
   skin_color
   }
}`
}

REST

{
   "data": {
      "user": {
      "id": 4,
      "name": "Tomisin Lalude",
      "age":  23,
     "skin_color": "Brown Skin"
      }
   }
}

If you look closely at the GraphQL structure, you'd realize the query is passed as a string (backticks are used in multi-line strings) inside a JSON object

while

The response is passed as an object in data inside a JSON object for a REST API.

So typically, a GraphQL query is not JSON, it is a string.

  1. The client (browser) sends the GraphQL query to the server as a string.
  2. The server validates this string
  3. The server then makes calls to the database to get the data values requested by the client (browser)
  4. The server returns this fetched data to the browser in a JSON object.

This is the client-server flow for when you want to fetch data.

However, you do not have to bother your head much about this flow. Just like in REST APIs where we use HTTP clients in handling responses, you can also use a GraphQL client to make queries.

Like so:

const client = new client("API_URL");

client.query(`
query {
    user {
    id
    name
    age
    skin_color
   }
}`)

I hope this article gives you an idea of how these APIs differ.

Thank you for reading.