GraphQL is an alternative to REST. Clients request exactly the data they need.
REST vs GraphQL¶
- REST: multiple endpoints, fixed responses
- GraphQL: single endpoint, flexible queries
- REST: over/under-fetching
- GraphQL: exactly what you need
Schema¶
type User {
id: ID!
name: String!
email: String
posts: [Post!]!
}
type Post {
id: ID!
title: String!
author: User!
}
Query¶
query {
user(id: "123") {
name
email
posts {
title
}
}
}
Mutation¶
mutation {
createUser(input: { name: "John", email: "[email protected]" }) {
id
name
}
}
Subscription (real-time)¶
subscription {
messageAdded(channelId: "general") {
id
text
author { name }
}
}
N+1 Problem¶
GraphQL resolver for posts can trigger N database queries. Solution: DataLoader for batching.
When to Use GraphQL¶
- Mobile apps (minimize network traffic)
- Complex nested data
- Multiple clients with different needs
- Real-time with subscriptions
When NOT to Use¶
- Simple CRUD API
- File uploads (REST is simpler)
- Caching (REST + CDN is simpler)
Recommendations¶
REST is sufficient for most APIs. Add GraphQL when you have complex data requirements or multiple clients.
graphqlapibackend