How to add mltiple variants to existing product using GraphQL

heyuuuuu
Tourist
21 0 1

I'm considering to add variants to existing product using GraphQL.

 

I have tried a code as below, but it dosen't work.

 

Dose anyone know why?

import requests

# Your Shopify store URL
shopify_url = "https://your-shopify-store.myshopify.com"

# Your Shopify access token
access_token = "your-access-token"

# GraphQL endpoint
graphql_url = f"{shopify_url}/admin/api/2023-10/graphql.json"

# Define the product ID (replace with your actual product ID)
product_id = "gid://shopify/Product/YOUR_PRODUCT_ID"

# List of product variants to create
variants_to_create = [
    {
        "title": "Variant 1",
        "price": "9.99",
        "sku": "SKU1"
    },
    {
        "title": "Variant 2",
        "price": "14.99",
        "sku": "SKU2"
    },
    {
        "title": "Variant 3",
        "price": "19.99",
        "sku": "SKU3"
    }
]

# Build the GraphQL mutation
variants_str = ', '.join([f'{{title: "{v["title"]}", price: "{v["price"]}", sku: "{v["sku"]}"}}' for v in variants_to_create])

mutation = """
mutation {
  productVariantCreate(input: {
    productId: "%s",
    variants: [%s]
  }) {
    productVariant {
      id
      title
    }
  }
}
""" % (product_id, variants_str)

headers = {
    "Content-Type": "application/json",
    "X-Shopify-Access-Token": access_token,
}

data = {
    "query": mutation
}

response = requests.post(graphql_url, json=data, headers=headers)

if response.status_code == 200:
    result = response.json()
    print("Product Variants Created:")
    print(result)
else:
    print(f"Failed to create product variants. Status Code: {response.status_code}")
    print(response.text)
Replies 3 (3)

SBD_
Shopify Staff
1829 269 407

Hey @heyuuuuu 

 

Do you have any error messages? Have you tired doing this outside of code first (like with Curl or Insomnia?)

Scott | Developer Advocate @ Shopify 

heyuuuuu
Tourist
21 0 1

@SBD_ 

Thanks for replying.

 

I have an error as below;

Product Variants Created:
{'errors': [{'message': "InputObject 'ProductVariantInput' doesn't accept argument 'variants'", 'locations': [{'line': 5, 'column': 5}], 'path': ['mutation', 'productVariantCreate', 'input', 'variants'], 'extensions': {'code': 'argumentNotAccepted', 'name': 'ProductVariantInput', 'typeName': 'InputObject', 'argumentName': 'variants'}}]}

 

SBD_
Shopify Staff
1829 269 407

Thanks! As the error suggests, ProductVariantCreate isn't expecting a 'variants' argument. Try the productVariantsBulkCreate mutation (which accepts a variant argument).

Scott | Developer Advocate @ Shopify