GraphQL
A query language for APIs — clients describe exactly what data they need. Single endpoint, typed schema, no over/under-fetching. Created by Facebook. More flexible than REST but adds complexity (schema, resolvers, caching).
Lee Byron, Nick Schrock, Dan Schafer · Created GraphQL at Facebook in 2012
- Complex frontends with varied data needs.
- Mobile apps (bandwidth-sensitive).
- When clients need flexible queries.
- Microservices federation.
- Simple CRUD (REST is simpler).
- When caching is critical (REST is easier).
- When team doesn't know GraphQL.
Definition
GraphQL is a query language for APIs. Schema defines types and fields. Clients send queries describing what they need; resolvers fetch the data. Single endpoint (POST /graphql). Introspection lets tools explore the API. Subscriptions for real-time.
Why it exists
REST returns fixed response shapes — over-fetching (too much data) and under-fetching (multiple requests). GraphQL lets clients specify exactly what they need in one query.
How it works
Define a schema (types, fields, resolvers). Client sends a query: { user(id: 1) { name, posts { title } } }. Server validates against schema, resolvers fetch fields, returns JSON matching the query shape. Apollo Server/Client are popular.
Scaling limits
Complexity (schema, resolvers, codegen). Caching is harder than REST. N+1 query problems (use DataLoader). DoS surface (clients can craft expensive queries — need cost analysis).
Cost shape
Free and open source. Apollo has paid tiers for federation/features.
Alternatives
- REST — Simpler, cacheable, less flexible.
- tRPC — Type-safe, TS-only, no schema.
- gRPC — Internal APIs, binary, typed.
Failure modes
- N+1 queries.
- Complexity.
- Caching difficulty.
- DoS from expensive queries.