Usage of GraphQL (original) (raw)

Last Updated : 9 Apr, 2026

GraphQL is a query language for APIs that lets clients request only the required data, making APIs more efficient than traditional approaches.

1. Fast Development

GraphQL is client-driven, meaning the client controls what data to request and receives only the required information, enabling efficient updates to the interface.

2. Contract Based Schema

A contract-based schema in GraphQL acts as a blueprint and agreement between the client and server, defining what data is available and how it can be requested.

**Example of contract based schema:

type book {
id: ID!
title: String!
author: User!
}

type ReaderID {
id: ID!
name: String!
email: String!
}

type Query {
getAllBooks: [book!]!
getBookById(id: ID!): book!
}

3. No Under-Fetching and Over-Fetching

GraphQL eliminates under-fetching and over-fetching problems by allowing clients to request exactly the data they need using queries defined by a contract-based schema.

**Example: Fetch the user’s name, the titles of their articles, and the names of the last two followers.

query {
user(id: "1") {
name
articles {
title
}
followers(last: 2) {
name
}
}
}

**Output:

{
"data": {
"user": {
"name": "Alen",
"articles": [
{ "title": "Learn GraphQL" },
{ "title": "API Design" }
],
"followers": [
{ "name": "A" },
{ "name": "B" }
]
}
}
}

4. Real-Time Data With Subscription

GraphQL subscriptions enable real-time data updates, allowing clients to receive data instantly when specific events occur on the server. This is especially useful for applications like chat apps or live notifications.

Subscription

A Subscription is a special GraphQL type that provides a stream of data instead of a single response.

type Subscription {
currentUpdate(Id: ID!): MessageAlert
}

Data Fetching in REST Vs GraphQL

GraphQL improves upon REST by solving issues like inflexibility, over-fetching, and under-fetching, enabling efficient data retrieval and better overall performance.

Fetching of Data Using REST

Data retrieval in REST is done through multiple resource-specific endpoints, such as /users/{id} for user data, with additional endpoints required for related resources, resulting in multiple API calls.

graphsql_2

A secondary endpoint /users/{id}/articles is used to retrieve the articles associated with a specific user, representing a related resource in REST.

graphsql_3

A third endpoint /users/{id}/followers is used to retrieve the follower data associated with the specified user, representing another related resource in REST.

graphsql_4

Fetching of Data Using GraphQL

Data retrieval in GraphQL is performed through a single endpoint, where the client specifies exactly what data is needed in a query and receives a precise, structured response.

graphsql_1