Skip to the workspace
Pebellslearn by building
GraphQL Queries  ›  Lesson

Fragments

Fragments 14 minA fragment is a named selection set with a type condition that can be spread into any place selecting that type, so shared fields are defined once and every query that uses them stays in step.

graphql / Fragments

Explore each scene at your own pace.

01 · The rule

The rule

Fragments

The bookshop shows a "book card" in three places: the Browse page, search results and an author's page. Each card needs the same title, price and author name. Copying those fields into three queries works until someone adds a cover image to the card and forgets one of them. Fragments keep one definition.

The rule

Name a selection once, spread it wherever that type appears.

A fragment is a named, reusable selection set tied to a type:

fragment BookCard on Book {
  title
  price
  author { name }
}
  • BookCard is its name.
  • on Book is its type condition: it may only be used where a Book is being selected.

Use it with a spread, three dots and the name:

query BrowsePage {
  books(first: 10) {
    ...BookCard
  }
}

query AuthorPage($id: ID!) {
  author(id: $id) {
    name
    books {
      ...BookCard
    }
  }
}

The spread is replaced by the fragment's fields, so the response has title, price and author keys directly. There is no BookCard key; fragments exist only in the query.

Rules the server checks:

  • A spread must fit its place: ...BookCard inside author { } fails, because an Author can never be a Book.
  • Every fragment defined in a document must be used.
  • Fragments cannot spread themselves, directly or in a loop.

There is also an inline fragment, ... on Book { title }, with a type condition but no name. It matters when a field can return several types, which the Schema section covers.

Frontend frameworks lean on fragments: each component declares the fragment it needs, and the page query spreads them. Change a component's fields and every page that shows it follows.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.