Using Query Variables
1. Declaring Variables
| Syntax | Detail |
|---|---|
$name: Type | Optional |
$name: Type! | Required |
$name: Type = default | Default value |
| Scope | Variables 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
| Form | Caller Behavior |
|---|---|
$id: ID! | Variables JSON must include id |
$id: ID | May omit; null permitted |
| Required arg + nullable var | Validation 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
| Client | Pattern |
|---|---|
| fetch | body: JSON.stringify({ query, variables }) |
| Apollo | useQuery(GET, { variables: { id } }) |
| urql | useQuery({ query, variables }) |
| Relay | useLazyLoadQuery(query, variables) |
7. Validating Variable Types
| Phase | Check |
|---|---|
| Validation | Variable types match argument types |
| Coercion | JSON values coerced to GraphQL types |
| Required | Missing 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
| Case | Behavior |
|---|---|
| Variable omitted on nullable | Treated as null |
| Variable null on non-null arg | Validation error |
| Variable null with default | Default value used |
10. Organizing Complex Variables
| Strategy | Benefit |
|---|---|
| Single input object | Add fields without changing op signature |
| Codegen TS types | Compile-time variable type checking |
| Builder pattern | Helper functions to build large filter inputs |