0
0
GraphQLquery~5 mins

Fragments for reusable selections in GraphQL

Choose your learning style9 modes available
Introduction

Fragments let you save parts of your data requests to use again. This helps you avoid repeating the same code.

When you want to get the same fields from different parts of your data.
When your query is getting long and you want to keep it neat.
When you need to update a field selection in many places at once.
When you want to share common data requests between different queries or mutations.
Syntax
GraphQL
fragment FragmentName on TypeName {
  field1
  field2
  ...
}

query {
  someData {
    ...FragmentName
  }
}

Fragments start with the keyword fragment, followed by a name and the type they apply to.

Use ...FragmentName inside queries to include the fragment fields.

Examples
This fragment selects id, name, and email from a User. The query uses it to get these fields for user with id 1.
GraphQL
fragment userFields on User {
  id
  name
  email
}

query {
  user(id: "1") {
    ...userFields
  }
}
This fragment selects title and content from Post. The query uses it to get these fields for recent posts.
GraphQL
fragment postFields on Post {
  title
  content
}

query {
  recentPosts {
    ...postFields
  }
}
Sample Program

This query gets a list of books with their titles and authors. The author fields come from the reusable fragment authorDetails.

GraphQL
fragment authorDetails on Author {
  id
  name
}

query {
  books {
    title
    author {
      ...authorDetails
    }
  }
}
OutputSuccess
Important Notes

Fragments must match the type they are defined on.

You can use fragments inside other fragments for more reuse.

Fragments help keep queries clean and easier to maintain.

Summary

Fragments save repeated field selections for reuse.

Use fragment keyword to define reusable parts.

Include fragments in queries with ...FragmentName.