GraphQL je alternativa k REST. Klient si říká o přesně ta data, která potřebuje.
REST vs GraphQL¶
- REST: multiple endpoints, fixed responses
- GraphQL: single endpoint, flexible queries
- REST: over/under-fetching
- GraphQL: přesně to, co potřebujete
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: “Jan”, email: “jan@example.com” }) {
id
name
}
}
Subscription (real-time)¶
subscription {
messageAdded(channelId: “general”) {
id
text
author { name }
}
}
N+1 problém¶
GraphQL resolver pro posts může vyvolat N database queries. Řešení: DataLoader pro batching.
Kdy GraphQL¶
- Mobile apps (minimalizace network traffic)
- Complex nested data
- Múltiple klienti s různými potřebami
- Real-time s subscriptions
Kdy NE¶
- Jednoduché CRUD API
- File upload (REST je jednodušší)
- Caching (REST + CDN je jednodušší)
Doporučení¶
Pro většinu API stačí REST. GraphQL přidávejte, když máte complex data requirements nebo multiple clients.