GraphQL — Explained with Examples
GraphQL is a query language for APIs that lets clients request exactly the data they need from a single endpoint using a strong type system.
GraphQL was developed internally by Facebook in 2012 and open-sourced in 2015. It solves a fundamental problem with REST: over-fetching and under-fetching of data.
The Over-Fetching Problem
In a REST API, the server decides what data to return. If you need a user’s name and email, but the endpoint returns name, email, address, phone, and 20 other fields, you’re over-fetching. With GraphQL, the client specifies exactly which fields it needs.
# GraphQL query — client asks for exactly what it wants
query {
user(id: 1) {
name
email
}
}// Response — only requested fields returned
{
"data": {
"user": {
"name": "Alice",
"email": "alice@example.com"
}
}
}Real-World Analogy
REST is like ordering a fixed combo meal — you get everything whether you want it or not. GraphQL is like ordering à la carte — you pick exactly what you eat. If you only want fries, you don’t pay for the burger and drink.
Schema and Types
GraphQL uses a schema written in Schema Definition Language (SDL) to define types and relationships:
type User {
id: ID!
name: String!
email: String!
posts: [Post!]!
}
type Post {
id: ID!
title: String!
content: String!
author: User!
}
type Query {
user(id: ID!): User
posts: [Post!]!
}Mutations and Subscriptions
Beyond queries (reading data), GraphQL supports:
- Mutations — for writing data (POST/PUT/DELETE equivalent)
- Subscriptions — for real-time updates over WebSocket
mutation {
createUser(name: "Charlie", email: "charlie@example.com") {
id
name
}
}Related Terms
REST, API Gateway, JSON, gRPC, WebSocket
Related Tutorial
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro