What is GraphQL? — Query Language for APIs Explained
Definition
GraphQL is a query language for APIs and a server-side runtime for executing queries, developed by Facebook and open-sourced in 2015. Unlike REST APIs that expose multiple fixed endpoints, a GraphQL API exposes a single endpoint and lets clients specify exactly what data they want in their query. This eliminates over-fetching (getting more data than needed) and under-fetching (needing multiple requests to assemble a complete response).
How It Works
A GraphQL API is built around a strongly-typed schema that defines all possible queries, mutations, and types. A client sends a query document to the /graphql endpoint over HTTP POST, specifying exactly which fields to return and for which nested relationships. The server validates the query against the schema, executes resolver functions to fetch the data, and returns a JSON response matching the query's shape. Mutations follow the same syntax but declare intent to modify data. Subscriptions use a persistent connection (typically WebSocket) to push real-time updates.
Common Use Cases
- ▸Building flexible data APIs for mobile apps where bandwidth matters
- ▸Aggregating data from multiple microservices into a single request
- ▸Powering frontend data layers with tools like Apollo Client and urql
- ▸Generating TypeScript types automatically from a GraphQL schema
- ▸Building developer-friendly APIs where clients dictate response shape
Example
query GetUser($id: ID!) {
user(id: $id) {
name
email
posts(limit: 5) {
title
publishedAt
}
}
}
# Response only contains the fields you asked forRelated Tools
FAQ
- Is GraphQL always better than REST?
- No. GraphQL is ideal when clients need flexible data shapes, multiple related resources in one request, or strong type safety. REST is simpler, easier to cache with HTTP semantics, and better for simple CRUD APIs. Many large systems use both.
- How does GraphQL handle versioning?
- GraphQL APIs typically avoid versioning by evolving the schema additively: adding new fields and marking old ones as deprecated. Clients that do not request deprecated fields are unaffected. This avoids the need for /v1, /v2 API versions.
- What is the N+1 problem in GraphQL?
- The N+1 problem occurs when resolving a list of N items each triggers an additional database query — N queries for N items plus 1 for the list itself. The standard solution is using DataLoader, which batches and deduplicates these queries.