Facebook has open-sourced GraphQL — a query language for APIs that solves the over-fetching and under-fetching problem of REST. How GraphQL works and when to use it.
Problems with REST APIs in the mobile era¶
REST APIs designed for web applications often do not work ideally for mobile clients. Typical problems:
- Over-fetching — the endpoint returns more data than the client needs
- Under-fetching — the client must call multiple endpoints for a single screen
- API versioning — every change requires a new endpoint or a new version
Facebook encountered these problems in 2012 when switching to a native mobile app. GraphQL is the result of internal R&D.
How GraphQL works¶
GraphQL is a query language — the client specifies exactly what data it needs:
query {
user(id: "123") {
name
email
posts(last: 5) {
title
createdAt
comments {
text
author { name }
}
}
}
}
One request, exactly the data you need. No unnecessary transfers, no waterfall requests.
Type system and introspection¶
A GraphQL schema defines the API’s type system:
type User {
id: ID!
name: String!
email: String
posts: [Post!]!
}
type Post {
id: ID!
title: String!
content: String
author: User!
}
type Query {
user(id: ID!): User
posts(limit: Int): [Post!]!
}
Introspection allows tools to automatically generate documentation and provide IDE autocomplete. GraphiQL — the interactive playground — is the killer feature for developers.
GraphQL vs REST: when to use which¶
GraphQL is not a replacement for REST in all scenarios:
- GraphQL — complex data models, mobile clients, many relationships between entities
- REST — simple CRUD, file upload/download, HTTP-level caching, public APIs with simple endpoints
For enterprise applications with a rich frontend, we recommend considering GraphQL as the primary API layer.
Conclusion: the future of API design¶
GraphQL changes the way we think about APIs. Shifting power to the client — which defines what it needs — is a fundamental shift. Watch the ecosystem (Relay, Apollo) and consider GraphQL for your next project with a complex data model.
Need help with implementation?
Our experts can help with design, implementation, and operations. From architecture to production.
Contact us