What is GraphQL?
An introduction to GraphQL — what it is, why it exists, and how it compares to REST APIs.
What is GraphQL?
GraphQL is a query language for APIs and a runtime for executing those queries against your data. It was developed internally by Facebook in 2012 and open-sourced in 2015. Unlike REST, where the server decides what data to send, GraphQL lets the client specify exactly what data it needs.
The Problem with REST
In a traditional REST API, you have multiple endpoints:
GET /api/users/123
GET /api/users/123/posts
GET /api/users/123/followers
This leads to two major issues:
- Over-fetching — You get more data than you need. For example, fetching a user might return 20 fields when you only need the name and avatar.
- Under-fetching — You don't get enough data in a single request, forcing multiple round-trips to the server.
How GraphQL Solves This
With GraphQL, there is typically one single endpoint (e.g., /graphql), and the client sends a query describing exactly what it wants:
{
user(id: "123") {
name
avatar
posts {
title
}
}
}
The server responds with exactly that shape of data — nothing more, nothing less:
{
"data": {
"user": {
"name": "John Doe",
"avatar": "https://example.com/avatar.jpg",
"posts": [
{ "title": "My First Post" },
{ "title": "Learning GraphQL" }
]
}
}
}
Key Benefits of GraphQL
- Precise data fetching — ask for exactly what you need
- Single endpoint — no more managing dozens of REST endpoints
- Strongly typed schema — the API is self-documenting
- Real-time updates — built-in subscription support
- Great developer tools — tools like GraphiQL and Apollo DevTools
GraphQL vs REST — Quick Comparison
| Feature | REST | GraphQL |
|---|---|---|
| Endpoints | Multiple (/users, /posts) | Single (/graphql) |
| Data fetching | Server decides | Client decides |
| Over-fetching | Common | Eliminated |
| Type system | Optional (OpenAPI) | Built-in |
| Learning curve | Low | Moderate |
When to Use GraphQL
GraphQL is ideal when:
- Your app has complex, nested data relationships
- You serve multiple clients (web, mobile, IoT) with different data needs
- You want to reduce the number of network requests
- You need a strongly-typed, self-documenting API
Key Takeaways
- GraphQL is a query language for APIs, not a database
- It solves over-fetching and under-fetching problems of REST
- The client describes the shape of the response
- It uses a single endpoint with a strongly-typed schema
In the next episode, we'll dive into Query Basics and learn the syntax for writing GraphQL queries.