GraphQL is a query language and runtime for APIs, developed by Facebook (Meta) in 2012 and open-sourced in 2015.
It provides a flexible and efficient way for clients to request exactly the data they need — nothing more, nothing less.
🧩 Key Idea
In GraphQL, the client defines the structure of the response.
Unlike REST, where you often have multiple endpoints (/users
, /users/1/posts
, etc.),
GraphQL typically has one endpoint (e.g., /graphql
) that can handle any query.
⚖️ GraphQL vs REST
Concept | REST | GraphQL |
---|---|---|
Endpoint structure | Multiple endpoints | Single endpoint |
Data fetching | Fixed data per endpoint | Client specifies data |
Over-fetching / Under-fetching | Common | Avoided |
Versioning | Often needs versions (v1, v2) | Not needed (schema evolves) |
🧠 Example Schema
Here’s a simple GraphQL schema for a blog app:
type User {
id: ID!
name: String!
email: String!
posts: [Post!]
}
type Post {
id: ID!
title: String!
content: String
author: User!
}
type Query {
users: [User!]
user(id: ID!): User
posts: [Post!]
}
This defines:
- Two object types (
User
,Post
) - Relationships between them
- A
Query
type — the entry point for fetching data
🔍 Example Query
Client Request:
{
user(id: "1") {
name
email
posts {
title
}
}
}
Server Response:
{
"data": {
"user": {
"name": "Alice",
"email": "alice@example.com",
"posts": [
{ "title": "GraphQL Basics" },
{ "title": "Advanced GraphQL" }
]
}
}
}
✅ The client asked for only name
, email
, and posts.title
— and got exactly that.
⚙️ Example Mutation
GraphQL also supports mutations (for changing data):
mutation {
createPost(
title: "Hello GraphQL",
content: "This is my first post!"
) {
id
title
}
}
Response:
{
"data": {
"createPost": {
"id": "101",
"title": "Hello GraphQL"
}
}
}
🧩 Example Setup (JavaScript)
Using Apollo Server (Node.js):
import { ApolloServer, gql } from "apollo-server";
const typeDefs = gql`
type Query {
hello: String
}
`;
const resolvers = {
Query: {
hello: () => "Hello, GraphQL!"
}
};
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
When you visit the endpoint, you can run:
{
hello
}
Response:
{
"data": {
"hello": "Hello, GraphQL!"
}
}
✅ Summary
Feature | Description |
---|---|
Language | Query language for APIs |
Developed by | Facebook (Meta) |
Main benefit | Clients get exactly the data they need |
Server endpoint | Usually one (/graphql ) |
Supports | Queries, Mutations, Subscriptions (real-time) |