Using Query Variables

1. Declaring Variables

SyntaxDetail
$name: TypeOptional
$name: Type!Required
$name: Type = defaultDefault value
ScopeVariables apply to entire operation

2. Using Variables in Arguments

Example: Variable usage

query Search($q: String!, $limit: Int = 20) {
  search(query: $q, first: $limit) { id }
}

3. Making Variables Required

FormCaller Behavior
$id: ID!Variables JSON must include id
$id: IDMay omit; null permitted
Required arg + nullable varValidation error if value is null

4. Setting Default Values

Example: Default variable

query Posts($first: Int = 10, $after: String) {
  posts(first: $first, after: $after) { id }
}

5. Using Input Objects as Variables

Example: Input object variable

mutation CreateUser($input: CreateUserInput!) {
  createUser(input: $input) { user { id } }
}

# JSON variables
{ "input": { "email": "a@b.co", "name": "Ada" } }

6. Passing Variables from Client

ClientPattern
fetchbody: JSON.stringify({ query, variables })
ApollouseQuery(GET, { variables: { id } })
urqluseQuery({ query, variables })
RelayuseLazyLoadQuery(query, variables)

7. Validating Variable Types

PhaseCheck
ValidationVariable types match argument types
CoercionJSON values coerced to GraphQL types
RequiredMissing required variables → error

8. Using Variables in Directives

Example: Variable-controlled directive

query U($withEmail: Boolean!) {
  me {
    name
    email @include(if: $withEmail)
  }
}

9. Handling Null Variables

CaseBehavior
Variable omitted on nullableTreated as null
Variable null on non-null argValidation error
Variable null with defaultDefault value used

10. Organizing Complex Variables

StrategyBenefit
Single input objectAdd fields without changing op signature
Codegen TS typesCompile-time variable type checking
Builder patternHelper functions to build large filter inputs