GraphQL Basics
How GraphQL lets clients request exactly the data they need from a single endpoint
Overview
GraphQL is a query language for APIs where the client describes exactly which fields it wants, and the server returns just that data. Unlike REST's many endpoints, GraphQL usually exposes a single endpoint and uses a typed schema to define what's available. This avoids over-fetching (getting fields you don't need) and under-fetching (needing many round trips).
Syntax / Usage
Clients send a query naming the fields they want. The response mirrors the shape of the query. Queries read data; mutations change it.
query {
user(id: 42) {
name
posts {
title
}
}
}
Examples
The response mirrors the query's structure exactly, under a data key:
{
"data": {
"user": {
"name": "Ada Lovelace",
"posts": [{ "title": "On Computing" }]
}
}
}
A mutation changes data and returns the fields you request back:
mutation {
createPost(title: "Hello", authorId: 42) {
id
title
}
}
Common Mistakes
- Expecting REST status codes — GraphQL often returns
200with anerrorsarray - Requesting deeply nested fields that trigger expensive database queries
- Forgetting that a single query can fetch too much and slow the server
- Treating the single endpoint like REST with many URLs
- Ignoring the schema's types, which define exactly what you can query
See Also
api-design-rest-basics api-design-http-methods api-design-pagination