How to Create Fragment in GraphQL: Syntax and Examples
In GraphQL, you create a fragment using the
fragment keyword followed by a name and the type it applies to, then specify the fields inside curly braces. Fragments let you reuse field selections across multiple queries or mutations to keep your code clean and consistent.Syntax
A GraphQL fragment is defined with the fragment keyword, followed by the fragment name, the on keyword, and the type it applies to. Inside curly braces, you list the fields you want to reuse.
- fragment: keyword to start fragment definition
- FragmentName: a unique name for the fragment
- on TypeName: specifies the GraphQL type this fragment applies to
- { fields }: the fields to include in the fragment
graphql
fragment FragmentName on TypeName {
field1
field2
nestedField {
subField
}
}Example
This example shows how to create a fragment for a User type and reuse it in a query to fetch user details.
graphql
fragment userDetails on User {
id
name
email
}
query getUsers {
users {
...userDetails
}
}Output
{
"data": {
"users": [
{ "id": "1", "name": "Alice", "email": "alice@example.com" },
{ "id": "2", "name": "Bob", "email": "bob@example.com" }
]
}
}
Common Pitfalls
Common mistakes when creating fragments include:
- Using the same fragment name more than once in the same query.
- Applying a fragment to the wrong type, causing errors.
- Forgetting to spread the fragment with
...inside queries or mutations.
Always ensure fragment names are unique and match the correct type.
graphql
query getUsers {
users {
userDetails # Wrong: missing spread operator
}
}
# Correct usage:
query getUsers {
users {
...userDetails
}
}Quick Reference
| Concept | Description | Example |
|---|---|---|
| fragment | Keyword to define a reusable fragment | fragment userDetails on User { id name } |
| Fragment Name | Unique name for the fragment | userDetails |
| on TypeName | Specifies the GraphQL type | on User |
| Fields | Fields included in the fragment | id, name, email |
| Spread operator | Use ... to include fragment in query | ...userDetails |
Key Takeaways
Use the fragment keyword with a unique name and type to create reusable field sets.
Include fragments in queries with the spread operator ... followed by the fragment name.
Ensure fragment names are unique and match the correct GraphQL type to avoid errors.
Fragments help keep queries clean and avoid repeating field selections.
Always test queries with fragments to confirm they return expected data.