GraphQL in Production · GraphQL Fundamentals for API Designers
Queries, Variables, Fragments and Operation Names
Write maintainable client operations and help the server observe them.
Always send named operations with variables (never string-interpolated values): names enable per-operation metrics, logging and persisted queries; variables enable validation and caching. Use fragments to colocate data requirements with UI components (a core idea of Relay). Aliases let you request the same field with different arguments. Directives like @include/@skip toggle fields based on variables.
Operation hygiene
| Practice | Benefit |
|---|---|
| Named operations | Per-operation metrics, logs, persisted queries |
| Variables | No injection/escaping; reusable documents; caching |
| Fragments colocated with components | Each component declares its own data needs |
| Aliases | Same field with different args in one request |
query ProductPage($id: ID!, $withReviews: Boolean!) {
product(id: $id) {
...ProductHeader
reviews(first: 5) @include(if: $withReviews) { edges { node { rating body } } }
}
related: products(filter: { similarTo: $id }, first: 4) { edges { node { ...ProductCard } } }
}
fragment ProductHeader on Product { id name price { amount currency } }
fragment ProductCard on Product { id name imageUrl }
Common pitfalls
- Building query strings with interpolation.
- Anonymous operations that are impossible to monitor.
- Huge shared fragments that over-fetch everywhere.
Key points
- Named operations + variables
- Colocated fragments
- Aliases and directives for flexibility
Further reading: GraphQL: Queries
Practice questions
Why should clients never interpolate values into GraphQL query strings?
Answer
It risks injection-style bugs, defeats validation and caching of documents, and prevents persisted queries; variables are typed and validated separately.
What problem do colocated fragments solve?
Answer
Each UI component declares the fields it renders, so data requirements stay in sync with components and parents don't over-fetch or under-fetch for children.
Open in the app to mark lessons complete, take notes and track your progress.