Features
- Client specifies exact data shape needed
- Strongly typed schema with introspection
- Single endpoint for all queries and mutations
- Real-time subscriptions via WebSocket
Pros
- Eliminates over-fetching and under-fetching
- Self-documenting API with built-in type system
- Excellent for complex, nested data relationships
Cons
- Complexity overhead for simple CRUD APIs
- N+1 query problem requires careful resolver design
- HTTP caching is harder than REST
Overview
GraphQL is a query language and runtime for APIs, developed by Facebook in 2012 and open-sourced in 2015. It allows clients to request exactly the data they need in a single request, solving REST’s over-fetching and under-fetching problems.
A GraphQL API is defined by a strongly typed schema that describes all available data and operations. Clients write queries against this schema, and the server resolves them. This approach is especially powerful for applications with complex data relationships, like social networks, e-commerce platforms, or content management systems.
When to Use
GraphQL excels when multiple clients (web, mobile, third-party) need different views of the same data, when data relationships are complex and nested, or when you want a self-documenting API. For simple CRUD or internal APIs, REST or tRPC may be simpler.
Getting Started
# Schema definition
type Query {
user(id: ID!): User
}
type User {
id: ID!
name: String!
posts: [Post!]!
}
// Query from client
const GET_USER = gql`
query GetUser($id: ID!) {
user(id: $id) {
name
posts { title }
}
}
`;