Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 37 ยท Writing Queries

Variables and Directives

Pass dynamic values safely with GraphQL variables, name your operations, and switch fields on or off with the @include and @skip directives.

So far every query had its values written straight into the text: book(id: "b1"). Real applications need the value to change: the book the user clicked, the page number, the search box contents. This lesson shows the right way, variables, and the wrong way, building query strings by hand. It also covers directives such as @include and @skip, which turn parts of a query on or off from the same variables.

Real servers and clients are shown read-only. The runnable examples are stand-ins: a small coercion function and a mini executor that supports variables and directives.

Variables

A query with variables has two parts: a definition in the operation header, and uses inside the body, written with a $:

GRAPHQL
query GetBook($id: ID!, $limit: Int = 3) {
  book(id: $id) {
    title
    reviews(limit: $limit) {
      stars
    }
  }
}
  • $id: ID! declares a variable called id, of type ID, and the ! makes it required.
  • $limit: Int = 3 is optional and defaults to 3 when the client sends nothing.
  • book(id: $id) uses the variable wherever a value could be written.

The actual values travel beside the query text, as a separate JSON object. Over HTTP the request body is (read-only):

JSON
{
  "query": "query GetBook($id: ID!, $limit: Int = 3) { book(id: $id) { title reviews(limit: $limit) { stars } } }",
  "variables": { "id": "b1" },
  "operationName": "GetBook"
}

Variable types are declared with the same syntax as in the schema: String, Int, Float, Boolean, ID, custom types, lists like [Int!], and input objects (see Input Types, Custom Scalars and Introspection). Before executing, the server coerces the values: it checks each one against the declared type and refuses the whole request if one is wrong.

JS Variable coercion

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

No output.

Look at what happened: the first request fills in the default limit: 3, the empty one reports a missing required variable, and "five" is rejected because it is not an Int. The server never runs a resolver with a bad value.

Why variables beat string building

You could assemble the query text yourself:

JavaScript
const query = `{ book(id: "${userInput}") { title } }`;

This is the GraphQL version of SQL injection. If userInput contains a quote and braces, the user can rewrite the query. It also breaks on innocent input like a title containing ". A second problem is caching and monitoring: with values glued into the text, every request has a different query string, so servers cannot cache parsed queries, build allow-lists of known queries (see Query Depth, Complexity and Other Attacks) or group metrics by operation. With variables the text is the same constant string every time.

The rule is simple: the query text is code, variables are data. Never put data into code.

Directives: @include and @skip

A directive is an annotation starting with @ that changes how a field or fragment is executed. Two are built into every GraphQL server:

  • @include(if: Boolean!) keeps the field only if the condition is true.
  • @skip(if: Boolean!) drops the field if the condition is true.

Combine them with variables to make one query serve several UI states:

GRAPHQL
query GetBook($id: ID!, $withAuthor: Boolean!, $compact: Boolean = false) {
  book(id: $id) {
    title
    year @skip(if: $compact)
    author @include(if: $withAuthor) {
      name
    }
  }
}

When $withAuthor is false, the author key is simply absent from the response (not null). The same document can drive a detailed page and a compact list, and the server only runs the resolvers that are kept. Servers may also define custom directives (@deprecated is a standard one in schemas; others appear in authorization and caching setups), which you will meet in later lessons.

Do not confuse these query directives with schema directives such as @deprecated. Both start with @, but schema directives are written in the SDL by the server's developers, while @include and @skip are written by clients in operations.

Operation names and multiple operations

A single document may contain several named operations. The client then chooses one with operationName:

GRAPHQL
query ListBooks { books { title } }
query GetBook($id: ID!) { book(id: $id) { title } }

If a document has more than one operation and no operationName is sent, the request is an error. Even with a single operation, naming it helps logs and tools, as mentioned in Your First Query.

A stand-in executor with variables and directives

The executor below puts everything together: it parses the operation header, coerces variables (with defaults and required checks), resolves $name references inside arguments, honors @include and @skip, and picks an operation by name. It is a teaching stand-in; a real server also checks every variable's type against the argument it is used for.

JS Variables, directives and operation names

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

No output.

Case 1 shows the author key missing entirely; case 2 shows year dropped by @skip. Cases 3 and 4 fail in variable coercion, before any field runs. In the injection demo, the glued string turned one book field into a query that also fetches stolen: book(id: "b2"), a field the application never intended to run. The variable version treated the hostile string as an ID that matches nothing, so book is null.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In query Q($id: ID!, $n: Int = 5), which variable is optional?

    ! makes $id required. $n has a default value (and is nullable), so the client may omit it.
  2. 2. Why are variables safer than building the query string yourself?

    Variables are sent separately and never parsed as GraphQL syntax, so user input cannot add fields or break the query. They also keep the query text constant for caching.
  3. 3. What does @include(if: false) do to a field?

    An excluded field is not executed and does not appear in the response at all.
  4. 4. A document has operations A and B. The request sends no operationName. What happens?

    With several operations the client must say which one to execute using operationName.

Summary

  • Variables are declared in the operation header ($id: ID!, optionally with a default) and used as $id inside the query.
  • Their values are sent separately as JSON in variables; the server coerces and validates them before execution.
  • Never interpolate user input into query text: it allows injection and defeats caching and allow-lists.
  • @include(if:) and @skip(if:) conditionally keep fields; excluded fields are absent from the response.
  • Name your operations; when a document has several, send operationName.

Next: Mutations and Subscriptions