Variables & Fragments — GraphQL

Variables ($id: ID!) keep the query text fixed, and their values travel separately in the variables JSON with keys without $, beside the operationName. That…

How do you use one query for book number 1, 2 or 3 without writing its text again? With a variable: a blank in a query whose value is sent separately, as JSON. Its partner, the fragment, solves a different problem: a named list of fields you can reuse in many places.

It's like the bookshop's order form. Its text is printed the same for every customer ("I'd like book number ___"); only what goes in the blank changes. That's a variable. A fragment is like a "title, price, author" stamp you can press onto any form.

The problem: values glued into the query text

The first idea is usually to glue the value into the query text with a template string:

const title = 'The Rainbow "Troops"'; // from the add-book form
const query = `mutation {
  createBook(input: { title: "${title}", authorId: 1, price: 89000, stock: 1 }) {
    id
  }
}`;

The quote in that title closes the GraphQL string early, so the server rejects the whole query: Syntax Error: Expected ":", found String "". Worse, a form value can be crafted on purpose to add other fields or arguments to your query. It's the same problem as SQL injection. And every value makes a different query text, so the server can't recognise "the same query" in its logs or cache.

Variables: $id and the JSON beside it

With a variable, the query text stays fixed. The value travels in another part of the request body:

query BookDetail($id: ID!) {
  book(id: $id) {
    title
    price
  }
}

Variables:

{ "id": 2 }
{ "data": { "book": { "title": "This Earth of Mankind", "price": 125000 } } }

From JavaScript, all three go in one body:

const response = await fetch("https://api.bookshop.test/graphql", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    query: BOOK_DETAIL, // the query text above, never changes
    operationName: "BookDetail",
    variables: { id: 2 },
  }),
});

Change { "id": 2 } to { "id": 3 } and the answer is Beauty Is a Wound, with exactly the same query text. A title with a quote in it is safe too, because a variable's value is never read as GraphQL text. It's just a value of type String.

Variable types, the exclamation mark and default values

The server checks the variables against their types before any resolver runs. If they don't fit, the whole request is rejected: the response has only errors, no data.

Sent for BookDetail($id: ID!) Message from graphql-js 17 Message from graphql-js 16 (used by Apollo Server 5)
{} Variable "$id" has invalid value: Expected a value of non-null type "ID!" to be provided. Variable "$id" of required type "ID!" was not provided.
{ "id": null } Variable "$id" has invalid value: Expected value of non-null type "ID!" not to be null. Variable "$id" of non-null type "ID!" must not be null.
{ "id": true } Variable "$id" has invalid value: ID cannot represent value: true Variable "$id" got invalid value true; ID cannot represent value: true

So forgetting id doesn't make book null, and the server doesn't guess id 1. The request is rejected before any resolver runs. The same goes for UpdateStock($id: ID!, $stock: Int!) with { "id": 2, "stock": "7" }: Variable "$stock" has invalid value: Int cannot represent non-integer value: "7" (graphql-js 16: Variable "$stock" got invalid value "7"; Int cannot represent non-integer value: "7"). Numbers in JSON are written without quotes. The other variable messages in this lesson are written as graphql-js 17 prints them. In graphql-js 16, has invalid value: reads got invalid value <value>;, and a required variable that was not sent reads of required type "ID!" was not provided.

A variable may have a default value, used when its key is missing from the JSON:

query BookList($status: StockStatus = IN_STOCK) {
  books(status: $status) {
    title
    stock
  }
}

A variable's type must be an input type (a scalar, an enum or an input), and it must fit where it's used. $id: ID without ! in book(id: ID!) is rejected during validation: Variable "$id" of type "ID" used in position expecting type "ID!". A whole input object can be one variable too: mutation AddBook($input: CreateBookInput!) with the JSON { "input": { "title": "The Dancer", "authorId": 4, "price": 95000, "stock": 3 } }.

Fragments: a list of fields used again

A book card in an app always needs the title, the price and the author's name. Rather than writing all three over and over, name them once:

query TwoBooks {
  rainbow: book(id: 1) {
    ...BookInfo
  }
  mankind: book(id: 2) {
    ...BookInfo
    stock
  }
}

fragment BookInfo on Book {
  title
  price
  author {
    name
  }
}
{
  "data": {
    "rainbow": { "title": "The Rainbow Troops", "price": 89000, "author": { "name": "Andrea Hirata" } },
    "mankind": { "title": "This Earth of Mankind", "price": 125000, "author": { "name": "Pramoedya Ananta Toer" }, "stock": 0 }
  }
}

The rules are strict. An unused fragment gets the whole document rejected: Fragment "BookInfo" is never used. A misspelled name: Unknown fragment "BookInf". Used on another type: Fragment "BookInfo" cannot be spread here as objects of type "Author" can never be of type "Book".

Inline fragments: ... on Type

For this lesson, the Bookshop schema gets a search field. A result can be a book or an author, so its type is a union:

type Query {
  # ...the fields it already has
  search(text: String!): [SearchResult!]!
}

union SearchResult = Book | Author

Each type's fields are asked for with an inline fragment, a fragment with no name written right where it's used:

query Search($text: String!) {
  search(text: $text) {
    __typename
    ... on Book {
      title
    }
    ... on Author {
      name
    }
  }
}

With the variables { "text": "ea" }:

{
  "data": {
    "search": [
      { "__typename": "Book", "title": "This Earth of Mankind" },
      { "__typename": "Book", "title": "Beauty Is a Wound" },
      { "__typename": "Author", "name": "Andrea Hirata" }
    ]
  }
}

... on Book { title } means "if this result is a Book, take its title". __typename tells the client its real type. Asking for title directly on search is rejected: Cannot query field "title" on type "SearchResult". Did you mean to use an inline fragment on "Book"?

@include and @skip

These two built-in directives drop a field depending on a Boolean variable:

query BookDetail($id: ID!, $withAuthor: Boolean!) {
  book(id: $id) {
    title
    author @include(if: $withAuthor) {
      name
    }
  }
}

{ "id": 1, "withAuthor": false } answers { "book": { "title": "The Rainbow Troops" } }. With true, author comes along. @skip(if: true) is the opposite: the field is dropped when the condition is true. Both also work on ...BookInfo and ... on Book. The variable must be Boolean! or have a default; $withAuthor: Boolean is rejected with Variable "$withAuthor" of type "Boolean" used in position expecting type "Boolean!".

Several operations in one document

One document may hold several named operations, say query Rainbow { ... } and query Mankind { ... }. The request must say which one to run, with operationName: "Mankind". Without it: Must provide operation name if query contains multiple operations. A name that isn't there: Unknown operation named "Beauty". The operation name is also what shows up in server logs and devtools, so pick a clear one.

⚠️ What gets a variable or fragment rejected

TL;DR: Variables ($id: ID!) keep the query text fixed, and their values travel separately in the variables JSON with keys without $, beside the operationName. That prevents injection and lets the query be reused. The server checks variables before any resolver runs: a required one that's missing or of the wrong type gets the request rejected with no data. A default ($status: StockStatus = IN_STOCK) is used when the key is missing, and null overrides it. A fragment (fragment BookInfo on Book, used with ...BookInfo) is a reusable list of fields that avoids duplication; an unused one is rejected. An inline fragment (... on Book) picks fields per type in a union like SearchResult. @include(if:) and @skip(if:) drop fields on a Boolean. A document with several operations needs an operationName.

⚡ Values glued into the query text

Guess first: the title The Rainbow "Troops" is glued into the query text with a template string. What does the server answer?

The whole query is rejected: Syntax Error: Expected ":", found String "". The quote in the title closes the GraphQL string early.

Meaning: A form value can even be crafted on purpose to add fields or arguments to your query, the same problem as SQL injection.

⚡ Variables: the query text stays fixed

Write:

query BookDetail($id: ID!) {
  book(id: $id) {
    title
    price
  }
}

Meaning: The value travels separately as JSON, { "id": 2 }, with a key without $. The query text never changes, so it's safe from injection and easy to reuse for any book.

⚡ Fragments: a list of fields used again

Write:

fragment BookInfo on Book {
  title
  price
  author {
    name
  }
}

Meaning: Write it once, then drop it in with ...BookInfo wherever a Book is asked for. When the book card needs a new field, change the fragment alone. A fragment that's never used gets the whole document rejected.

What you will learn