0
0
GraphqlHow-ToBeginner · 3 min read

How to Query with Default Values in GraphQL

In GraphQL, you can set default values for query arguments by specifying them in the query operation's argument list using =. 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.

graphql
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.

graphql
query getBooks($limit: Int = 3) {
  books(limit: $limit) {
    title
    author
  }
}
Output
[ { "title": "The Great Gatsby", "author": "F. Scott Fitzgerald" }, { "title": "1984", "author": "George Orwell" }, { "title": "To Kill a Mockingbird", "author": "Harper Lee" } ]
⚠️

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.

graphql
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 missing
📊

Quick Reference

ConceptSyntaxDescription
Variable with default($varName: Type = defaultValue)Defines a variable with a default value
Use variablefield(arg: $varName)Pass variable to query field argument
No variable passedN/ADefault value is used automatically
Direct argument defaultNot supportedDefault values only work with variables

Key Takeaways

Always define default values for query variables to avoid errors when variables are missing.
Default values are set in the query operation's variable definitions using = syntax.
Default values apply only to variables, not to direct field arguments.
Using default values simplifies client queries and improves API usability.