Variables in GraphQL
Hardcoding values in queries works for testing, but production code should use variables.
Instead of:
query {
user(id: 1) {
name
}
}
Use:
query GetUser($userId: ID!) {
user(id: $userId) {
name
}
}
Then pass variables separately:
{
"userId": "1"
}
Why variables?
- Reusability - Same query, different values
- Security - No string interpolation means no injection attacks
- Caching - Query structure stays constant, only values change
The $userId: ID! declares the variable type. The ! means it's required.
In Python, you pass variables as a dictionary alongside the query.
I explain variable patterns in my GraphQL with Python course.