Skip to main content

GraphQL variables

Note

The REST Admin API is a legacy API as of October 1, 2024. All apps and integrations should be built with the GraphQL Admin API. For details and migration steps, visit our migration guide.

Legacy

The REST Admin API is a legacy API as of October 1, 2024. All apps and integrations should be built with the GraphQL Admin API. For details and migration steps, visit our migration guide.

You can simplify GraphQL queries and mutations by extracting data into separate variables. GraphQL variables let you reuse the same requests with different arguments.


GraphQL requests can be split into query and variable sections.

In the query section, GraphQL variables begin with the $ symbol and are declared after the query or mutation keyword, similar to passing an argument to a function.

When you declare a variable, you need to specify its type, such as CustomerInput. This lets GraphQL know that you intend to refer to this type by this variable name later in the actual query.

For example, the following query declares an $input variable and passes it to the input argument:

GraphQL mutation with an input variable

mutation($input: CustomerInput!) {
customerCreate(input: $input) { ... }
}

In the variable section, variables are defined as a JSON object.

The following JSON object defines the $input variable for the query section:

Input variables

{
"input": {
"firstName": "Ayumu",
"lastName": "Hirano",
"email": "ayumu@example.com"
}
}

Anchor to Simplify the customer creation requestSimplify the customer creation request

The following example simplifies the customerCreate mutation example by using variables, resulting in an abstracted mutation that can be reused to create multiple customers.

POST /admin/api/{api_version}/graphql.json

GraphQL mutation

mutation ($input: CustomerInput!) {
customerCreate(input: $input)
{
customer {
id
displayName
}
userErrors {
field
message
}
}
}

Input variables

{
"input": {
"firstName": "Ayumu",
"lastName": "Hirano",
"email": "ayumu@example.com"
}
}

JSON response

{
"data": {
"customerCreate": {
"customer": {
"id": "gid://shopify/Customer/1310038130710",
"displayName": "Ayumu Hirano"
},
"userErrors": []
}
}
...
}

Learn how to optimize your GraphQL implementation further with inline fragments and multi-query requests.


Was this page helpful?