How to Use Variables in GraphQL Mutation
In GraphQL, you use
variables in mutations by defining them in the mutation signature with a dollar sign (e.g., $id) and passing their values separately in a variables object. This approach keeps your mutation flexible and secure by separating query structure from data.Syntax
To use variables in a GraphQL mutation, you declare them in the mutation's parameter list with a dollar sign and specify their type. Then, you use these variables inside the mutation body. When sending the mutation, you provide the actual values in a separate variables object.
- Variable declaration: Inside parentheses after the mutation name, e.g.,
mutation ($id: ID!) - Variable usage: Use the variable name with a dollar sign inside the mutation, e.g.,
id: $id - Variables object: A JSON object sent alongside the mutation with actual values, e.g.,
{ "id": "123" }
graphql
mutation UpdateUser($id: ID!, $name: String!) {
updateUser(id: $id, name: $name) {
id
name
}
}Example
This example shows a mutation to update a user's name using variables for the user's ID and new name. The mutation defines variables $id and $name, then uses them in the updateUser mutation. The variables object provides the actual values.
graphql
mutation UpdateUser($id: ID!, $name: String!) {
updateUser(id: $id, name: $name) {
id
name
}
}
# Variables JSON:
{
"id": "123",
"name": "Alice"
}Output
{
"data": {
"updateUser": {
"id": "123",
"name": "Alice"
}
}
}
Common Pitfalls
Common mistakes when using variables in mutations include:
- Not declaring variables in the mutation signature but trying to use them inside the mutation.
- Mismatch between variable names in the mutation and in the variables object.
- Not providing required variables or providing wrong types.
- Forgetting the dollar sign
$when using variables inside the mutation body.
Example of wrong and right usage:
graphql
# Wrong: variable used but not declared
mutation {
updateUser(id: $id) {
id
}
}
# Right: variable declared and used
mutation UpdateUser($id: ID!) {
updateUser(id: $id) {
id
}
}Quick Reference
| Step | Description | Example |
|---|---|---|
| Declare variables | Define variables with types in mutation signature | mutation ($id: ID!) |
| Use variables | Use variables with $ inside mutation body | updateUser(id: $id) |
| Send variables | Pass actual values in variables JSON | {"id": "123"} |
| Match names | Ensure variable names match in all places | Variable $id used and declared |
| Use correct types | Types must match schema requirements | ID!, String!, Int |
Key Takeaways
Always declare variables with types in the mutation signature using $.
Use variables inside the mutation body with the $ prefix.
Pass actual variable values separately as a JSON object when executing the mutation.
Ensure variable names and types match between declaration, usage, and variables object.
Avoid hardcoding values inside mutations to keep them reusable and secure.