0
0
GraphqlHow-ToBeginner · 3 min read

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

ConceptDescriptionExample
fragmentKeyword to define a reusable fragmentfragment userDetails on User { id name }
Fragment NameUnique name for the fragmentuserDetails
on TypeNameSpecifies the GraphQL typeon User
FieldsFields included in the fragmentid, name, email
Spread operatorUse ... 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.