Why Was GraphQL Created?
GraphQL was designed to solve problems that became increasingly visible as client applications became more sophisticated.
A traditional REST API often models server resources through endpoints. That model works well for many applications, but complex user interfaces can require data from many related resources.
Imagine a social application displaying a user's profile, recent posts, author information, comments, and reactions. A REST client might need several requests:
GET /users/42
GET /users/42/posts
GET /posts/101/comments
GET /posts/101/reactions
This can create several problems.
Over-fetching
An endpoint may return fields that the client does not need. A mobile application might only require a user's name and avatar, while /users/42 returns dozens of additional fields.
Under-fetching
A response may not contain enough information to render the screen, forcing the client to make additional requests.
Endpoint proliferation
As application requirements grow, teams may add increasingly specialized endpoints for different clients and screens.
Client-specific requirements
A web application, mobile application, admin application, and smart TV application may need different representations of the same underlying data.
GraphQL addresses these issues by allowing clients to select the fields they need from a typed graph of related data.
However, GraphQL is not automatically better than REST in every situation. REST remains an excellent choice for many APIs. The correct choice depends on requirements such as caching strategy, operational complexity, team experience, API consumers, and data access patterns.
Receiving fields that are not requiredNeeding multiple requestsIncreasing number of specialized endpoints- GraphQL was created to improve flexibility for data-driven clients.
- Over-fetching means receiving unnecessary fields.
- Under-fetching can force clients to make additional requests.
- GraphQL solves specific API design problems but is not universally superior to REST.
A mobile screen needs only a user's name and profile image, but the REST endpoint returns 30 additional fields. What problem does this demonstrate?