I’m following the GraphQL documentation for `productCreate but I can’t figure out how to add multiple variants when creating a product.
I’m using the following mutation:
mutation productCreate($input: ProductInput!) {
productCreate(input: $input) {
userErrors {
field
message
}
shop {
id
}
product {
title
handle
variants {
edges {
node {
title
}
}
}
}
}
}
And passing the following variables:
{
"input": {
"title": "Testing Products",
"handle": "test-product-2",
"variants": [
{ "title": "Variant 1" },
{ "title": "Variant 2" }
]
}
}
The error I am getting back is:
{
"data": {
"productCreate": {
"userErrors": [
{
"field": [
"variants",
"1"
],
"message": "The variant 'Default Title' already exists."
}
],
"shop": {
"id": "gid://shopify/Shop/59898691733"
},
"product": null
}
},
"extensions": {
"cost": {
"requestedQueryCost": 12,
"actualQueryCost": 10,
"throttleStatus": {
"maximumAvailable": 1000,
"currentlyAvailable": 990,
"restoreRate": 50
}
}
}
}
I’ve scoured the internet trying to figure out how to add multiple variants when creating a product on Shopify, but I can’t figure it out.
Is it possible to do this?
2 Answers
I was defining the variants wrong. Without the options
key (which is odd that it’s plural considering it only takes a string?) it wouldn’t work.
{
"input": {
"title": "Testing Products",
"handle": "test-product-2",
"variants": [
{
"title": "Size Small",
"options": "Small"
},
{
"title": "Size Medium",
"options": "Medium"
},
{
"title": "Size Large",
"options": "Large"
}
]
}
}
I also ran into this error today (The variant ‘Default Title’ already exists.)
What I finally figured out works best is to make sure you specify the options array on the main product. And then also define the options on the variants like so:
{
"input":
{
"handle": "my-product",
"title": "My Product",
"options": ["Size", "Color"],
"variants": [
{
"sku": "1111",
"title": "My Product Small Green",
"options": ["Small", "Green"]
},
{
"sku": "1112",
"title": "My Product Medium Green",
"options": ["Medium", "Green"]
},
{
"sku": "1113",
"title": "My Product Small Red",
"options": ["Small", "Red"]
},
{
"sku": "1114",
"title": "My Product Medium Red",
"options": ["Medium", "Red"]
}
]
}
}
If you don’t specify the options array on the main product your variants won’t have a proper label.