Problems GraphQL Solves
The bookshop's mobile home screen shows a book, its author and two reviews. With a typical REST API that takes three requests (/books/b1, /authors/a1, /books/b1/reviews), and each reply carries dozens of fields the screen never uses. On a slow phone network, both of those costs hurt.
The rule
One request, only the fields you need, from one evolving schema.
Each part of the rule answers a classic API pain:
- Under-fetching: one endpoint does not return enough, so the client makes follow-up requests, often one after another because it needs an ID from the first reply. GraphQL lets one query follow links: book, then its author, then its reviews.
- Over-fetching: an endpoint returns a fixed bundle, so every client downloads fields it ignores. In GraphQL each client selects its own fields.
- Versioning: REST teams often ship
/v2/when a response must change. A GraphQL schema grows instead: add new fields freely, mark old ones@deprecated, and remove them once no client asks for them. - A weak contract: GraphQL's schema is typed and can be queried by tools (this is called introspection), so editors can autocomplete fields and catch mistakes before a request is sent.
query {
book(id: "b1") {
title
author { name }
reviews(first: 2) { rating }
}
}That single query replaces the three REST calls, and returns only four kinds of values.
GraphQL is not free. The server is more complex to build, HTTP caching by URL works less naturally because most requests are POST to one endpoint, and a careless client can write a very expensive query. Teams accept those costs when many different clients need different slices of the same data.