GraphQL variables
You can simplify GraphQL queries and mutations by extracting data into separate variables. GraphQL variables let you reuse the same requests with different arguments.
Variable structure
Anchor link to section titled "Variable structure"GraphQL requests can be split into query and variable sections.
Query section
Anchor link to section titled "Query section"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:
Variable section
Anchor link to section titled "Variable section"In the variable section, variables are defined as a JSON object.
The following JSON object defines the $input
variable for the query section:
Simplify the customer creation request
Anchor link to section titled "Simplify 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.
Learn how to optimize your GraphQL implementation further with inline fragments and multi-query requests.