GraphQL
Beginner
1 min read
Fragments and Inline Fragments
Example
# ----- Named Fragment -----
fragment ProductFields on Product {
id
name
price
category { name }
}
query ListProducts {
featured: products(featured: true) {
...ProductFields
}
sale: products(onSale: true) {
...ProductFields
discountPercent
}
}
# ----- Inline Fragments on Union -----
query Search($term: String!) {
search(term: $term) {
__typename # returns "Product", "User", etc.
... on Product {
name
price
}
... on User {
email
role
}
... on Category {
name
productCount
}
}
}
# ----- Inline Fragment on Interface -----
query GetNodes($ids: [ID!]!) {
nodes(ids: $ids) {
id # from Node interface
... on User { email }
... on Post { title }
... on Order { total }
}
}
Related Resources
GraphQL Reference
Complete tag & property list
GraphQL How-To Guides
Step-by-step practical guides
GraphQL Exercises
Practice what you've learned
More in GraphQL