GraphQL mutations and variables
GraphQL mutations create and modify objects, similar to a PUT, POST, or DELETE request in REST. Mutation requests are sent to the same
/admin/api/2019-04/graphql.json endpoint as query requests.
Mutations have the following structure:
- The name of a mutation, such as
- The data to use in the mutation passed as an argument, such as the information for a new customer
- A selection of return fields that should be included in the response, such as the ID of the successfully created Customer object
Mutations require input data, such as the data to create a new object, or the ID of an object to delete. For mutations that might require a substantial data object, the schema provides a dedicated input object type.
For example, the customerCreate mutation requires an
input argument, which accepts a CustomerInput object. The CustomerInput type defines all the fields that can be used to create or modify a customer:
Each mutation provides a set of fields that can be returned in the response. For example, one of the return fields available for the customerCreate mutation is the Customer object that was created by a successful mutation. As with a GraphQL query, you can select the fields on the new object that you want to include in the response.
Each mutation can return the
userErrors field. The
userErrors field returns information about errors when a mutation fails. You should include the
userErrors field with each mutation to make it easier to troubleshoot failed mutations.
You can simplify GraphQL queries and mutations by extracting data into separate variables. GraphQL variables begin with the
$ symbol and are declared after the
mutation keyword, similar to passing an argument to a function. When you declare a variable, you need to specify it's type, such as
The exclamation mark after the variable type shows that the variable is required. You can pass variables to GraphQL queries and mutations as JSON. The following mutation creates a customer by using the variable
Create a customer
The cURL command below creates a customer. The JSON
data object has two properties:
query— The mutation, provided as a string.
variables- An object for holding variables. The only variable is the
inputobject used for the mutation.
To run the cURL command from the command line, make the following substitutions:
< store >— The name of your development store.
< access_token >— Your access token.
The response will look similar to this:
- Paginating results with GraphQL — Learn how to use cursor-based pagination with GraphQL.