Variables and operation names

Beginner · 9 min

Send values separately from the query text with typed variables, set defaults, name operations, and pick one operation from a document with several.

Before thisArgumentsFragments

ShopifyDevs · 9 min

Variables and operation names

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by ShopifyDevsReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A variable is declared in the operation header, query GetBook($id: ID!), used in the body as $id, and its value travels in a separate JSON object.
  • Variables keep the query text constant so it can be cached, logged, and persisted, and they avoid building queries by string concatenation, which invites injection bugs.
  • Each variable has a type that the validator checks against the position where it is used; a mismatch such as an Int used where ID! is expected is rejected.
  • A variable can have a default, $withAuthor: Boolean = false, and a nullable variable may be omitted.
  • A document with more than one operation must say which to run through operationName; a single operation can stay anonymous, though naming it helps logs and tooling.

Values do not belong in the query

So far every query had its values written in: book(id: "12"). That is fine at a prompt. It falls apart in an application. To fetch the book the user clicked on, the code would have to build a string:

const query = `{ book(id: "${id}") { title } }` // do not do this

Two problems. The query text is now different for every id, so nothing can cache it, group it in logs, or recognise it. And a value with a quote in it breaks the syntax or, if it comes from a user, changes the meaning, the same shape as SQL injection.

GraphQL has the standard answer: variables. The query declares typed placeholders, and the values travel next to it as JSON.

query GetBook($id: ID!, $withAuthor: Boolean = false) {
  book(id: $id) {
    title
    author @include(if: $withAuthor) { name }
  }
}
{ "id": "10", "withAuthor": true }

The header query GetBook($id: ID!, ...) does two jobs. GetBook is the operation name. $id: ID! declares a variable with its type. In the body, $id is used wherever a value could go. The query text never changes. Only the JSON does.

What I ran

Against graphql-js 17.1.0, with the operation above (plus a $n: Int argument for books(limit: $n)):

Variables Result
{"id":"10"} book without author ($withAuthor defaulted to false), all books
{"id":"10","withAuthor":true,"n":1} book with author, one book
{} Variable “$id” has invalid value: Expected a value of non-null type “ID!” to be provided.
{"id":10} accepted: ID coerces the integer
{"id":"10","n":"one"} Variable “$n” has invalid value: Int cannot represent non-integer value: “one”

The server checks the values against the declared types before running anything. Variable values are coerced exactly like literals, with one difference: they arrive as JSON, so a custom scalar’s parseValue is used, not parseLiteral (scalar types).

Types must line up

The variable’s declared type must fit where it is used. This is checked statically:

query Q($n: Int) { book(id: $n) { title } }
# Variable "$n" of type "Int" used in position expecting type "ID!".

A nullable variable cannot feed a non-null position. If a field needs ID!, declare $id: ID!. A variable with a default value is allowed in a non-null position, since the default fills the gap.

Other rules, tested: a variable declared and never used is an error (“Variable “$unused” is never used in operation “Q”“), and variables are scoped to their own operation.

Operation names

You have written anonymous operations: { ... }, or query { ... }. You can name any operation:

query GetBook { ... }
mutation DeleteBook { ... }

A name is optional when the document holds a single operation, and required when it holds several. Here is a document with two:

query A { book(id: "10") { title } }
query B { book(id: "12") { title } }

Sending it with no operationName gets “Must provide operation name if query contains multiple operations.” Setting operationName to B ran only B and returned Cosmos. An unknown name gives Unknown operation named "C". Over HTTP the name is its own key of the JSON body (GraphQL over HTTP); in graphql() it is the operationName option.

Even when it is optional, always name your operations. The name shows up in server logs, error trackers, traces, and tools that count what a client asks for. “GetBook is slow” is something you can act on. “An anonymous query is slow” is not. Many teams enforce naming with a lint rule.

Defaults and optional variables

A variable can have a default:

query($limit: Int = 10) { books(limit: $limit) { title } }

If the client sends nothing for limit, 10 is used. A nullable variable with no default can be left out; the field then sees it as “not provided” and, in turn, applies the argument’s own default, if any. You will usually pair optional variables with optional arguments.

Variables and the rest of the stack

Variables make several later topics possible. Persisted queries (persisted queries) work because the text is constant: the client sends a hash and the variables. Caching in clients keys on the operation plus variables. Code generation produces a TypeScript type for the variables of each named operation (code generation and typed operations).

What the video covers

ShopifyDevs’ “How to use GraphQL Operation Names and Variables - 1 of 5” is a little over nine minutes, published November 2020, and is the first of a five-part language-features playlist. Its description says the presenter demonstrates the benefits of using names and variables when working with queries. It is from a company channel whose demos likely use Shopify’s own API, which I could not confirm without a transcript; the concepts are the standard ones. If you prefer a modern, shorter slice, the My Digital Diaries EP04 episode has a variables chapter (00:45 to 04:42) and is linked as the runner-up.

Where this fits

Variables can also drive the shape of a query, switching fields on and off. That is the job of directives. Next: directives.

Check yourself

  1. 01Why use variables instead of writing values straight into the query?

    The query text stays the same across calls, which allows caching and persisting it, and values are passed as typed data rather than spliced into a string.

  2. 02What happens if a required variable such as $id: ID! is missing from the variables JSON?

    Execution does not start, and the server returns an error saying the variable has an invalid value because it expected a value of the non-null type to be provided.

  3. 03A document has queries named A and B. How do you run B?

    Send operationName set to B alongside the query and variables, because without it the server reports that it must provide an operation name.

  4. 04Why does the validator reject a variable declared but never used?

    An unused variable is almost always a mistake, so the spec makes it an error, as in Variable $unused is never used in operation Q.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark