Arguments and Variables
Arguments allow a client to provide input to a field.
For example:
query {
user(id: "42") {
id
name
}
}
Here id: "42" is an argument.
Hardcoding values directly into the query is not ideal for reusable application code. GraphQL therefore provides variables.
query GetUser($id: ID!) {
user(id: $id) {
id
name
}
}
Variables are supplied separately:
{
"id": "42"
}
The declaration $id: ID! specifies the variable type. The operation then passes $id into the field argument.
Variables provide several benefits:
- They allow query reuse.
- They separate operation structure from runtime values.
- They allow GraphQL to validate variable types.
- They avoid constructing query strings manually for ordinary dynamic values.
Default variable values are also possible:
query Products($limit: Int = 20) {
products(limit: $limit) {
id
name
}
}
When the client omits limit, the default value of 20 is used according to GraphQL's variable semantics.
Query with Variables
query GetProducts($category: String!, $limit: Int = 10) {
products(category: $category, limit: $limit) {
id
name
price
}
}💡 The query declares two variables.
category is required because it uses String!. limit is optional because it has a default value. Runtime values are supplied separately from the GraphQL document.Key Takeaways
- Arguments provide values to GraphQL fields.
- Variables separate runtime values from query structure.
- Variable types are validated against the schema.
- Default variable values can simplify optional parameters.
Knowledge Check
Where are GraphQL variable values normally supplied?