How to Use Variables in GraphQL Query: Simple Guide
In GraphQL, use
variables by declaring them in the query signature with a dollar sign (e.g., $id) and passing their values separately in a variables object. This lets you reuse queries with different inputs without changing the query text itself.Syntax
GraphQL variables are declared in the query's parentheses with a dollar sign and a type. You then use the variable inside the query by referencing its name with a dollar sign. The actual values are sent separately in a variables object.
- Variable declaration:
($variableName: Type!)declares a variable namedvariableNameof a specificType. - Using variable: Inside the query, use
$variableNamewhere you want to insert the value. - Variables object: When sending the query, provide a JSON object with keys matching variable names and their values.
graphql
query GetUser($id: ID!) {
user(id: $id) {
name
email
}
}Example
This example shows a GraphQL query that fetches a user's name and email by their ID using a variable. The variable $id is declared and used in the query, and the value is passed separately.
graphql
query GetUser($id: ID!) {
user(id: $id) {
name
email
}
}
# Variables JSON:
{
"id": "123"
}Output
{
"data": {
"user": {
"name": "Alice",
"email": "alice@example.com"
}
}
}
Common Pitfalls
Common mistakes when using variables in GraphQL include:
- Not declaring variables in the query signature but trying to use them inside the query.
- Passing variables with wrong names or missing required variables in the variables object.
- Using incorrect types or forgetting to mark required variables with
!.
Always ensure variable names match exactly and types are correct.
graphql
query WrongUsage {
user(id: $id) { # Error: $id not declared
name
}
}
# Correct usage:
query CorrectUsage($id: ID!) {
user(id: $id) {
name
}
}Quick Reference
| Concept | Description | Example |
|---|---|---|
| Variable Declaration | Declare variables with name and type in query signature | ($id: ID!) |
| Variable Usage | Use variables inside query with $ prefix | user(id: $id) |
| Variables Object | Pass values as JSON when sending query | {"id": "123"} |
| Required Variable | Add ! to type to make variable required | ($id: ID!) |
| Optional Variable | No ! means variable can be null or omitted | ($id: ID) |
Key Takeaways
Declare variables in the query signature with their types using $variableName syntax.
Use variables inside the query by prefixing with $ and pass their values separately in a variables object.
Always match variable names and types exactly between query and variables object.
Mark variables as required with ! if they must be provided.
Variables make queries reusable and dynamic without changing query text.