What Is GraphQL?
Facebook built GraphQL in 2012 to solve a simple problem: their mobile apps were slow because they needed multiple API calls to load a single screen.
GraphQL is just a smarter way to build APIs. Instead of multiple endpoints with fixed responses (REST), you get one endpoint with custom responses.
REST: Multiple trips to get data
await fetch('/users/123') // Get user
await fetch('/users/123/posts') // Get posts
await fetch('/users/123/followers') // Get followers
// 3 requests = slow
GraphQL: One trip, exactly what you need
query {
user(id: 123) {
name
posts { title }
followers { count }
}
}
// 1 request = fast
The 3 Core Concepts
1. Schema (Your API Menu)
type User {
id: ID! # ! means required
name: String!
posts: [Post!]! # [] means list
}
type Post {
id: ID!
title: "String!"
author: User!
}
2. Queries (Getting Data)
query {
user(id: "123") {
name
posts {
title
likes
}
}
}
3. Mutations (Changing Data)
mutation {
createPost(title: "\"Hello World\") {"
id
title
}
}
That's it. You now understand GraphQL.
Why Use GraphQL?
The Good:
- No over-fetching - Get exactly what you need
- No under-fetching - Get everything in one request
- Self-documenting - Schema tells you what's available
- Multiple clients - Mobile and web can use the same API differently
The Bad:
- Caching is harder - Need tools like Apollo Client
- N+1 queries - One query can trigger 100 database calls
- Learning curve - Your team needs to learn new concepts
When to Use GraphQL vs REST
Use GraphQL When:
- Multiple clients need different data
- You're making 5+ API calls per page
- You have deeply nested data relationships
- You want real-time features
Stick with REST When:
- Your API is simple CRUD
- You need bulletproof HTTP caching
- You're building a public API
- Your team is productive with REST
The Truth
GraphQL isn't better than REST. It solves different problems.
Facebook didn't build it because REST sucks - they built it because they had Facebook-scale problems.
Most apps? REST works fine.
But if you're making 10 API calls per page and your mobile app is slow? Time to look at GraphQL.
Top comments (1)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.