Skip to the workspace
Pebellslearn by building
GraphQL Queries  ›  Lesson

Aliases

Aliases 10 minAn alias renames a field's key in the response, which lets one selection ask for the same field several times with different arguments without the results colliding.

graphql / Aliases

Explore each scene at your own pace.

01 · The rule

The rule

Aliases

The bookshop home page has two shelves side by side: "Fantasy picks" and "Mystery picks". Both come from the same field, books, with different genres. Ask for books twice in one query and the server refuses, because the response would need two keys called books. Aliases solve this.

The rule

newName: field renames the key; it lets one field be asked twice.

An alias goes before a field, followed by a colon. It changes the key in the response, and nothing else:

{
  fantasy: books(genre: FANTASY, first: 2) {
    title
  }
  mystery: books(genre: MYSTERY, first: 2) {
    title
  }
}
{
  "data": {
    "fantasy": [{ "title": "The Salt Road" }, { "title": "Lanterns at Dusk" }],
    "mystery": [{ "title": "The Quiet Ledger" }, { "title": "Nine Locked Doors" }]
  }
}

Each field in a response has a response name: its alias if it has one, otherwise its field name. Inside one selection set, two fields with the same response name must be mergeable, which means the same field with the same arguments. So:

  • title title is fine; the two merge into one title key.
  • books(genre: FANTASY) { title } books(genre: MYSTERY) { title } is an error; one key cannot hold two different answers.

Aliases are also handy for renaming a key to suit your code, such as heading: title. The schema and the resolver are untouched; only the JSON key changes.

Aliases work at any depth, not just at the root. A book page that wants the single newest review for a banner and the five newest for a list can ask for both inside one book:

{
  book(id: "b1") {
    newest: reviews(first: 1) { rating text }
    recent: reviews(first: 5) { rating }
  }
}
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.