![]() |
VOOZH | about |
GraphQL is a query language for APIs that lets clients request only the required data, making APIs more efficient than traditional approaches.
GraphQL is client-driven, meaning the client controls what data to request and receives only the required information, enabling efficient updates to the interface.
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!
}
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" }
]
}
}
}
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.
A Subscription is a special GraphQL type that provides a stream of data instead of a single response.
type Subscription {
currentUpdate(Id: ID!): MessageAlert
}
GraphQL improves upon REST by solving issues like inflexibility, over-fetching, and under-fetching, enabling efficient data retrieval and better overall performance.
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.
A secondary endpoint /users/{id}/articles is used to retrieve the articles associated with a specific user, representing a related resource in REST.
A third endpoint /users/{id}/followers is used to retrieve the follower data associated with the specified user, representing another related resource in REST.
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.