What Is GraphQL? A Modern Alternative to REST APIs
Is your frontend fetching more data than it needs? Making multiple API calls to build a single page? GraphQL lets you get exactly the data you need in a single request.
What Is GraphQL?
GraphQL is an API query language and runtime open-sourced by Facebook in 2015. The client defines exactly what data it needs; the server returns precisely that — nothing more, nothing less.
REST vs GraphQL
REST: GET /users/42 → Entire user object (unnecessary fields)
GET /users/42/posts → Second request
GET /users/42/comments → Third request
GraphQL: POST /graphql → Single request, exact data you need
| Feature | REST | GraphQL | |---------|------|---------| | Endpoints | Multiple | Single | | Data volume | Over/Under-fetching | Exact amount | | Versioning | /v1/, /v2/ | No versioning | | Documentation | Separate (Swagger) | Auto-generated | | Learning curve | Low | Medium |
Core Concepts
Schema
Your API's type-safe contract:
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(limit: Int): [Post!]!
}
type Mutation {
createPost(title: String!, content: String!): Post!
}
Query (Read)
query {
user(id: "42") {
name
email
posts {
title
}
}
}
Response:
{
"data": {
"user": {
"name": "Ali",
"email": "ali@example.com",
"posts": [
{ "title": "GraphQL 101" }
]
}
}
}
Mutation (Write)
mutation {
createPost(title: "New Post", content: "Content...") {
id
title
}
}
Subscription (Real-time)
subscription {
newPost {
id
title
author { name }
}
}
Apollo Server Example
const { ApolloServer, gql } = require('apollo-server');
const typeDefs = gql`
type User {
id: ID!
name: String!
}
type Query {
users: [User!]!
user(id: ID!): User
}
`;
const resolvers = {
Query: {
users: () => db.users.findAll(),
user: (_, { id }) => db.users.findById(id),
},
};
const server = new ApolloServer({ typeDefs, resolvers });
When to Choose GraphQL vs REST
Choose GraphQL when:
- Multiple clients (web, mobile, IoT) need different data shapes
- You have deeply nested, relational data
- Frontend teams want independence from backend changes
Choose REST when:
- Simple CRUD operations
- File upload/download
- HTTP caching is critical
- Team lacks GraphQL experience
Best Practices
- Solve the N+1 problem — Use DataLoader for batched queries
- Apply depth limiting — Prevent excessively nested queries
- Use cursor-based pagination — For large datasets
- Standardize error handling — Consistent error response format
- Adopt schema-first design — Design the schema before implementing
Conclusion
GraphQL revolutionizes frontend-backend communication by eliminating over-fetching and under-fetching. However, it's not the right choice for every project — REST still works perfectly for simple APIs.
Learn API design and GraphQL interactively on LabLudus.