Introduction to GraphQL in comparision with REST

Ashok Vishwakarma
Ashok Vishwakarma

Aug 26, 2018 • 4 min read

Introduction to RESTful Web Services (REST APIs)

Everybody is building or using REST APIs in their web/mobile application, REST is an acronym for Representational State Transfer (REST), as per wikipedia which means

An architectural style that defines a set of constraints to be used for creating web services. — wikipedia

In simple words when an API is developed by following these defined set of rules we call it a RESTful web service or RESTful API, the most important rules from these defined sets are as follows

Every RESTful API consist of many endpoints which represent the object or model on which the operations can be performed, the rule says every endpoint (URL) must represent by a noun (your model name) for example

# endpoint for User model
https://api.com/user

# endpoint for Category model
https://api.com/category

# endpoint for Post model
https://api.com/post

And the operation (Add, Update, Delete and etc) on these endpoints must perform using HTTP methods (GET, PUT, POST, DELETE) for example

# list all the user
GET https://api.com/user

# get the user having passed id
GET https://api.com/user/:id

# create a new user
POST https://api.com/user

# update the user have passed id
PUT https://api.com/user/:id

# delete the user having passed id
DELETE https://api.com/user/:id

Every web/mobile application have relationships between their model either 1:1 (one to one), 1:M (one to many) or M:M (many to many). The response for these relationship in RESTful APIs should be as follows

# response for a post with its category
# Post and Category have 1:1 relationship
{
id: 1,
title: "GraphQL - 101",
category: "/category/1",

...

status: 1
}

Links which represent the related model in the response, which requires another HTTP call to fetch the details on related model, but if there is any way we can get the details of related model in the first response for example

{
id: 1,
title: "GraphQL - 101",
category: {
name: "Category 1",

...
}

...

status: 1
}

In RESTful APIs there are two ways you can do this, using a different endpoint or using query string for example

# using difrerent end-point
GET https://api.com/post/1/withCategory

//using query string
GET https://api.com/post/1?includeCatyegory

But these two approaches have some problems, suppose our UI only require Category Name instead of all the fields from Category model or it also require User information with the post and etc etc. In every such scenario we end up creating a new endpoint or adding a new query string property into the endpoint which will be very difficult to manage or write documentation.

What if there are some mechanism which allow to send the required information onto an endpoint and in response we receive the exact same information we have requested, for example

# endpoint
https://api.com/graphql

# query
query post(id: 1) {
id,
title,
description,
category {
name
},
user {
firstName,
lastName,
avatar
}
}

# response
{
id: 1,
title: "GraphQL - 101",
description: "...",
category: {
name: "101"
},
user: {
firstName: "Ashok",
lastName: "Vishwakarma",
avatar: "..."
}
}

This is exactly what GraphQL is.

Introduction to GraphQL

GraphQL is an open source initiative by Facebook and published under BSD-3 license. As per their website https://graphql.org it is a query language for our API which fulfil those queries with our data on runtime.

Response based on the Request

GraphQL makes sure that you’ll only receive the information you have requested by sending a POST request to your GraphQL endpoint

# GraphQL request
{
query user() {
id,
firstName,
lastName,
avatar
}
}

# GraphQL response
[{
id: 1,
firstName: "Ashok",
lastName: "Vishwakarma",
avatar: "..."
}]

# Updated GraphQL request
{
query user() {
id,
firstName,
lastName,
avatar,
friend {
firstName,
lastName,
avatar
}
}
}

# Updated GraphQL response
[{
id: 1,
firstName: "Ashok",
lastName: "Vishwakarma",
avatar: "...",
friends: [{
fistName: "...",
lastName: "...",
avatar: "..."
}]
}]

As you can see in both the examples your API code remain same and consumer is able to get appropriate response by updating the request, this will allow API consumers to get desired result from the same API endpoint.

Single Endpoint and Types

Unlike RESTful APIs, GraphQL only have a single endpoint which is organised using Types which can be queried as standalone or related to each other.

# A typical GrahpQL endpoint
https://api.your-domain.com/graphql

Types in GraphQL help to ensure that the App only asks what is possible and also helps in providing clear error messages when something is requested but not available.

# GraphQL types

type Query {
users: [User]
}

type User {
id: String,
firstName: String,
lastName: String,
avatar: String,
friends: [User]
}

In the above type example we have query and User types, where friends for user is also an User type which is an example of relation between types

# Simple GraphQL request

{
query users {
firstName,
lastName,
avatar,
friends {
firstName,
lastName,
avatar
}
}
}

In the above GraphQL request we are querying the users query with desired fields from User type and also the friends relation. The firstName fields we have queried in users and friends will be from the same User type as they both are same type.

Updates without versioning

GraphQL is very helpful when it comes to updating the existing APIs, adding new fields and type doesn’t effect the existing responses same as for removing a fields or types.

type query {
posts: [Post]
}

type Post {
id: string,
title: String,
description: String,
user: User
}

type User {
id: String,
firstName: String,
lastName: String,
avatar: String
}

# Updated Post Type
type Post {
id: String,
title: String,
description: String,
user: User @depricated
createdBy: User
}

In the above example in the Post type user field is deprecated and a new field createdBy is added using @depricated type casting on the fields will be suggest consumer to user createdBy instead of user property which ensure the consumer is using latest features and maintain a single API version all the time.

Developer tool

GraphQL provides a default developer tool to access all the available Types, Queries and Mutations defined in the API which helps consumer to understand the response format better.

The developer tool can be accessible directly on the GraphQL endpoint.

# Developer tool URL
https://api.your-domain.com/graphql

Conclusion

In a nutshell GraphQL solves many problems in RESTful APIs we face on daily basis, it works as a wrapper on existing APIs without changing it at all.

This article is to provide a brief introduction of GraphQL and its awesome features which are helping our APIs to become more dynamic and robust, it also helps the consumer to be free and known for the every request and its possible response without visiting the API documentation again again.

I will be publishing other GraphQL articles for Getting Started and In Depth understanding. Keep watching this space.

Please share this article with everyone and make their life easy as API developer or consumer. Also don’t forget to comment your suggestions.


Ashok Vishwakarma

Ashok Vishwakarma

Google Develover Expert — WebTechnologies and Angular | Principal Architect at Naukri.com | Entrepreneur | TechEnthusiast | Speaker