You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shopify GraphQL:使用Python创建带变体商品报optionValues字段不存在错误

使用Python+GraphQL创建Shopify带变体商品报错解决

问题重现

尝试通过Python调用Shopify GraphQL API创建带变体的商品时,执行代码后返回错误:

{
  "errors": [
    {
      "message": "Field 'optionValues' doesn't exist on type 'ProductOption'",
      "locations": [
        {
          "line": 15,
          "column": 9
        }
      ],
      "path": [
        "mutation CreateProductWithOptions",
        "productCreate",
        "product",
        "options",
        "optionValues"
      ],
      "extensions": {
        "code": "undefinedField",
        "typeName": "ProductOption",
        "fieldName": "optionValues"
      }
    }
  ]
}

原代码如下:

import requests
import json

# Shopify API credentials
shop_url = "ShopURL"
access_token = "access_token"

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

# Build the GraphQL mutation to create a product with options and option values
mutation = """
mutation CreateProductWithOptions($input: ProductInput!) {
  productCreate(input: $input) {
    userErrors {
      field
      message
    }
    product {
      id
      options {
        id
        name
        position
        values
        optionValues {
          id
          name
          hasVariants
        }
      }
      variants(first: 5) {
        nodes {
          id
          title
          selectedOptions {
            name
            value
          }
        }
      }
    }
  }
}
"""

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

# Define the variables with the product input
variables = {
  "input": {
    "title": "New product",
    "optionValues": [
      {
        "name": "Color",
        "values": [
          {
            "name": "Red"
          },
          {
            "name": "Green"
          }
        ]
      },
      {
        "name": "Size",
        "values": [
          {
            "name": "Small"
          },
          {
            "name": "Medium"
          }
        ]
      }
    ]
  }
}

# Create the request data
data = {
    "query": mutation,
    "variables": variables
}

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

if response.status_code == 200:
    result = response.json()
    print("Product with options and option values created:")
    print(json.dumps(result, indent=2))
else:
    print(f"Failed to create the product. Status Code: {response.status_code}")
    print(response.text)

错误原因

  1. 查询字段错误:Shopify GraphQL API的ProductOption类型中不存在optionValues字段,你在查询返回的product.options里误用了这个字段。ProductOption对应的选项值字段是values(字符串数组)。
  2. 输入参数错误:创建商品的ProductInput中,定义选项的参数是options,而非optionValues,参数名不符合API规范。

修正后的代码

核心修正点

  • 移除查询语句中options下的optionValues字段
  • 将变量中的optionValues键名改为options,保持和API输入结构一致

完整修正代码:

import requests
import json

# Shopify API credentials
shop_url = "ShopURL"
access_token = "access_token"

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

# 修正后的GraphQL mutation
mutation = """
mutation CreateProductWithOptions($input: ProductInput!) {
  productCreate(input: $input) {
    userErrors {
      field
      message
    }
    product {
      id
      options {
        id
        name
        position
        values
      }
      variants(first: 5) {
        nodes {
          id
          title
          selectedOptions {
            name
            value
          }
        }
      }
    }
  }
}
"""

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

# 修正后的输入变量
variables = {
  "input": {
    "title": "New product",
    "options": [
      {
        "name": "Color",
        "values": ["Red", "Green"]
      },
      {
        "name": "Size",
        "values": ["Small", "Medium"]
      }
    ]
  }
}

# Create the request data
data = {
    "query": mutation,
    "variables": variables
}

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

if response.status_code == 200:
    result = response.json()
    print("带变体的商品创建成功:")
    print(json.dumps(result, indent=2, ensure_ascii=False))
else:
    print(f"创建失败,状态码:{response.status_code}")
    print(response.text)

验证结果

执行修正后的代码,会返回成功创建的商品数据,包含正确的选项和变体信息,示例返回片段:

{
  "data": {
    "productCreate": {
      "userErrors": [],
      "product": {
        "id": "gid://shopify/Product/123456789",
        "options": [
          {
            "id": "gid://shopify/ProductOption/123",
            "name": "Color",
            "position": 1,
            "values": ["Red", "Green"]
          },
          {
            "id": "gid://shopify/ProductOption/456",
            "name": "Size",
            "position": 2,
            "values": ["Small", "Medium"]
          }
        ],
        "variants": {
          "nodes": [
            {
              "id": "gid://shopify/ProductVariant/12345",
              "title": "Red / Small",
              "selectedOptions": [
                {"name": "Color", "value": "Red"},
                {"name": "Size", "value": "Small"}
              ]
            }
          ]
        }
      }
    }
  }
}

内容的提问来源于stack exchange,提问作者yoooku

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 22:05:58