What GraphQL Is and How It Differs from REST
A query language for your API
GraphQL is a query language for APIs, created at Facebook. Instead of many fixed endpoints that each return a fixed shape, GraphQL exposes a single endpoint where the client asks for exactly the data it needs, in the shape it needs, and gets back exactly that – nothing more, nothing less.
The REST problems it solves
Classic REST tends to two problems:
- Over-fetching: an endpoint returns 30 fields when the screen needs 3.
- Under-fetching: getting a user, then their posts, then each post's comments takes several round trips.
GraphQL lets the client fetch a user, their posts and those posts' comments in one request, choosing precisely the fields.
A query and its response
query {
user(id: 1) {
name
posts {
title
}
}
}
The JSON response mirrors the query shape exactly – user.name and a list of posts with only title. The client, not the server, decides the shape.
What GraphQL is not
GraphQL is not a database or a replacement for your data layer – it sits in front of it. It is also not automatically “better” than REST; REST is simpler for basic CRUD and benefits from HTTP caching. GraphQL shines when clients are varied and data is graph-shaped.
Key points
- GraphQL is an API query language with a single flexible endpoint.
- Clients request exactly the fields they need, avoiding over- and under-fetching.
- The response shape mirrors the query shape.
- It complements your data layer; it is not a database or a strict upgrade over REST.