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. = 3gives 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.
The shortcut
To turn a hard-coded query into a reusable one, lift, declare, send.
Lift
Spot the values that change per click:
MYSTERYand3. Replace them with$genreand$first.
A common slip is putting quotes around enum values in the query text. In the variables JSON they are strings, but inside the query they are bare words.
Drills
Answer fast — trust the rule.
How do you ask for mystery books directly in the query text?
Where do the values for variables travel?
query ($id: ID!) { book(id: $id) { title } } is sent with no variables. What happens?
Why is query ($first: Int = 5) { books { title } } invalid?
With query ($first: Int = 5) { books(first: $first) { title } } and variables { "first": 2 }, how many books come back at most?
Remember
- Arguments shape a field; variables feed arguments from outside.
- Lift the changing values, declare them with types, send them as JSON.
- Trap: quoting enum values in query text, or declaring a variable you never use.
