How to Query with Default Values in GraphQL
=. This means if the client does not provide a value, the default is used automatically. For example, query getBooks($limit: Int = 5) { books(limit: $limit) { title } } uses 5 as the default limit if none is provided.Syntax
To use default values in GraphQL queries, define variables with default values in the query operation's parameter list. The syntax is ($variableName: Type = defaultValue). If the client omits the variable, the default is used.
Inside the query, use the variable as usual. This helps avoid errors and simplifies client requests.
query getItems($count: Int = 10) {
items(limit: $count) {
id
name
}
}Example
This example shows a GraphQL query with a default value for the $limit variable. If no value is passed, the server returns 3 items by default.
query getBooks($limit: Int = 3) {
books(limit: $limit) {
title
author
}
}Common Pitfalls
One common mistake is forgetting to provide a default value and then not passing the variable, which causes an error. Another is setting default values in the resolver instead of the query, which is less flexible.
Also, default values only work for variables, not for direct arguments inside the query fields.
query getBooks($limit: Int) {
books(limit: $limit) {
title
}
}
# Wrong: No default and no variable passed causes error
query getBooks($limit: Int = 5) {
books(limit: $limit) {
title
}
}
# Correct: Default value prevents error if variable is missingQuick Reference
| Concept | Syntax | Description |
|---|---|---|
| Variable with default | ($varName: Type = defaultValue) | Defines a variable with a default value |
| Use variable | field(arg: $varName) | Pass variable to query field argument |
| No variable passed | N/A | Default value is used automatically |
| Direct argument default | Not supported | Default values only work with variables |