Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 37 ยท Writing Queries

Aliases and Fragments

Use GraphQL aliases to request the same field twice and fragments to stop repeating selections. Covers named and inline fragments with type conditions.

Two small features keep real-world queries tidy. Aliases let you rename a field in the response, which solves the problem of asking for the same field twice. Fragments let you name a group of fields once and reuse it, so a screen with five book cards does not repeat the same six lines five times. Both are pure query syntax: the schema does not change.

In this lesson you will use both and then build a stand-in that expands fragments the way a server's executor does. Remember that the executor code is a teaching stand-in, not a real GraphQL server.

The problem aliases solve

Response keys are the field names. So what happens here?

GRAPHQL
{
  books(genre: FANTASY, limit: 1) { title }
  books(genre: SCIFI, limit: 1) { title }
}

Both fields would write to the key books, and they have different arguments, so the server cannot merge them. This query is rejected as a conflict. An alias gives each one a different response key. You write alias: fieldName:

GRAPHQL
{
  fantasy: books(genre: FANTASY, limit: 1) { title }
  scifi: books(genre: SCIFI, limit: 1) { title }
}

The response now uses your names:

JSON
{
  "data": {
    "fantasy": [{ "title": "A Wizard of Earthsea" }],
    "scifi": [{ "title": "The Dispossessed" }]
  }
}

Aliases are also handy for renaming awkward fields to what your UI calls them (cover: imageUrl) and for asking for the same field with different arguments at any depth, such as small: avatar(size: 32) next to large: avatar(size: 256).

Here is a stand-in executor with alias support. In the parser the only change from the previous lesson is that when a field name is followed by a colon, the first name becomes the alias.

JS Aliases in action

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first query fails with a conflict error, just as a real server's validation does (the wording differs). The aliased version succeeds, and renaming title to name changes only the response keys, not the data.

Fragments: name a selection once

Imagine a page that shows a featured book, the latest book and a search result, each as a "book card" with the same fields:

GRAPHQL
{
  featured: book(id: "b1") { title year genre author { name } }
  latest: book(id: "b4") { title year genre author { name } }
}

A fragment names the shared part. You declare it once with fragment Name on TypeName { ... } and use it with ...Name, the spread:

GRAPHQL
fragment BookCard on Book {
  title
  year
  genre
  author { name }
}

{
  featured: book(id: "b1") { ...BookCard }
  latest: book(id: "b4") { ...BookCard }
}

Two parts of the declaration matter. The name (BookCard) is how you refer to it. The type condition (on Book) says which type the fragment applies to; the server checks that you only spread it where a Book can appear. Spreading BookCard inside an author { ... } selection would be a validation error.

Fragments are not only about saving keystrokes. In front-end apps, each UI component often owns a fragment describing the data it needs (BookCard for the card, AuthorBadge for the badge), and the page query simply spreads them. Change what the card shows, and only its fragment changes. Client libraries such as Relay are built around this idea; see Clients, Apollo and Code Generation.

Inline fragments and type conditions

Some fields can return more than one type. A search field might return books or authors. You can only select fields that exist on every possible type, plus __typename, so for type-specific fields you need an inline fragment, an unnamed fragment written right where you need it:

GRAPHQL
{
  search(text: "gu") {
    __typename
    ... on Book {
      title
      year
    }
    ... on Author {
      name
      born
    }
  }
}

For each result the server checks the actual type. Book results include title and year; Author results include name and born. __typename is a built-in meta field available on every object; it returns the type's name as a string and is how clients tell the cases apart. The schema side of this (interfaces and unions) is the topic of Enums, Interfaces and Unions.

Inline fragments are also used without a type condition, to attach a directive to a group of fields.

A stand-in fragment expander

How does a server turn all this into one flat list of fields per object? It runs a collect fields step: walk the selection list; plain fields are kept (merged when they share a response key), a fragment spread or inline fragment is replaced by its fields if its type condition matches the object's type, and skipped otherwise. This stand-in implements exactly that idea, with an exact type-name match only; real GraphQL also matches interfaces and unions.

JS Expanding fragments

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the output, featured and latest share the BookCard fields, and latest also repeats year, which the collect step merges rather than duplicating (real servers do the same). Within found, each result got only the fields for its own type, and __typename told us which was which.

Use a fragment when the same selection appears twice or when a component owns its data needs. Don't create fragments for a single use: a one-off fragment only moves text away from where it is used.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does { books(genre: FANTASY) { title } books(genre: SCIFI) { title } } fail?

    Response keys must be unique per object. Aliases (fantasy: books(...)) give each field its own key.
  2. 2. In fragment BookCard on Book { title }, what does on Book do?

    The type condition lets the server check the fragment is used on a compatible type and decide at run time whether to apply it.
  3. 3. When do you need an inline fragment such as ... on Author { name }?

    Fields that return interfaces or unions can only expose the shared fields directly; type-specific ones go inside a type-conditioned fragment.
  4. 4. What does __typename return?

    It is a built-in meta field present on every object type, and clients use it to tell union and interface members apart.

Summary

  • An alias (newName: field) changes the response key; it lets you request the same field several times with different arguments.
  • A named fragment (fragment Name on Type { ... }) holds a reusable selection, used with ...Name.
  • Fragment type conditions are checked by validation and decide at execution time whether the fields apply.
  • Inline fragments (... on Type { ... }) select type-specific fields from interface and union results.
  • __typename reports an object's type and powers client-side type switching.
  • Servers flatten fragments into one merged field list per object; the stand-in shows that process.

Next: Variables and Directives