Skip to the workspace
Pebellslearn by building
GraphQL Queries  ›  Lesson

Arguments and Variables

Arguments 14 minArguments are named values that shape what a field returns, and variables let a query declare typed placeholders for those values so the query text stays fixed while the values are sent separately as JSON.

graphql / Arguments and Variables

Explore each scene at your own pace.

01 · The rule

The rule

Arguments and Variables

The Browse page gets a genre filter. Clicking "Mystery" should show three mystery books; clicking "Fantasy" should show three fantasy ones. You could build a new query string for every click, but GraphQL gives you a cleaner pair of tools: arguments on fields, and variables that feed them.

The rule

Arguments shape a field; variables feed arguments from outside.

Arguments are named values in parentheses after a field. Any field the schema allows can take them, at any depth:

{
  books(genre: MYSTERY, first: 3) {
    title
    reviews(first: 2) { rating }
  }
}

Strings go in double quotes (id: "b1"), numbers and booleans are bare, and enum values are bare words (MYSTERY, not "MYSTERY"). Argument order does not matter; names do.

Hard-coding MYSTERY means a different query text for every click. Variables fix that. Declare them after the operation name, each starting with $ and carrying a type, then use them where values would go:

query BooksByGenre($genre: Genre!, $first: Int = 3) {
  books(genre: $genre, first: $first) {
    title
  }
}

The values travel separately, as JSON next to the query:

{ "genre": "MYSTERY" }

The rules:

  • A type ending in ! is required: the request fails if it is missing.
  • = 3 gives a default used when no value is sent.
  • Variables can only hold input values: scalars, enums and input object types, never output objects like Book.
  • Every declared variable must be used, and every used variable must be declared.

Because the query text never changes, clients can reuse it, tools can check it once, and nobody pastes user input into a query string.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.