👉 GraphQL = Graph Query Language
It is a query language for APIs and a runtime for executing those queries.
💡 Created by Facebook (2012) and open-sourced in 2015.
Instead of multiple API calls (like in REST), GraphQL lets you:
Ask exactly what you need 📦
Get all data in a single request ⚡
Avoid over-fetching or under-fetching 🔥
Feature | REST 🌍 | GraphQL 🔮 |
---|---|---|
Data Fetching | Multiple endpoints (e.g., /users , /posts ) |
Single endpoint (/graphql ) |
Response | Fixed structure 📑 | Flexible, defined by the query 🎨 |
Over-fetching | Common (extra unused data) 😩 | No, you get only what you asked ✅ |
Versioning | Needs /v1/ , /v2/ |
No versioning – schema evolves |
Speed | Slower with many endpoints 🐢 | Faster, optimized queries 🚀 |
Defines the shape of data (like a contract).
Types: Query
, Mutation
, Subscription
type User {
id: ID!
name: String!
age: Int
}
Used to fetch data.
query {
user(id: 1) {
name
age
}
}
👉 Only returns name
& age
(not the whole user object).
Used to write/update/delete data.
mutation {
createUser(name: "Abhi", age: 30) {
id
name
}
}
Used for real-time updates (like chats, stock prices).
subscription {
newMessage {
id
content
}
}
✅ Precise data fetching – no extra baggage
✅ Single endpoint – easy integration
✅ Strongly typed schema – predictable responses
✅ Great for mobile apps – reduces data usage 📱
✅ Real-time capabilities with subscriptions ⚡
⚡ More complex server setup
⚡ Caching is harder than REST
⚡ Security concerns (deep nested queries can overload server)
⚡ Learning curve 📚
Client 📱 → sends query 🎯 → GraphQL Server 🔮 → fetches from DB 📂 → returns only what client asked ✨
Imagine you want a user profile page:
In REST, you may need 3 calls: /user/1
, /user/1/posts
, /user/1/friends
.
In GraphQL, you just write:
query {
user(id: 1) {
name
posts {
title
}
friends {
name
}
}
}
👉 And BOOM! 💥 You get all data in one request.
🎨 In simple words:
GraphQL is like going to a restaurant buffet 🍲 and telling the chef:
💬 "I only want 2 slices of pizza 🍕 and 1 bowl of salad 🥗"
Instead of REST where they serve you the whole buffet whether you need it or not. 😅