跳至內容
ShopentlyLearn

建立 — 產品

使用下文描述的資料,在「產品」中執行「建立」操作。

POST/api/v1/products

身份驗證
Bearer
最低方案
STANDARD
所需權限
catalog.product:create
特定欄位所需的附加權限
  • variant_value_ids 非空時: catalog.product_variant:create
瞭解更多

程式碼範例

請求示例

cURL

: "${SHOPENTLY_SHOP_URL:?}"

curl --disable --globoff --fail-with-body --silent --show-error \
  --proto '=https' --connect-timeout 5 --max-time 30 \
  --request POST \
  --header "Authorization: Bearer ${SHOPENTLY_ACCESS_TOKEN:?}" \
  --header 'Idempotency-Key: example-create_product_api_v1_products_post' \
  --header 'Content-Type: application/json' \
  --data-raw '{
  "name": "Example",
  "sku": "example"
}' \
  --url "${SHOPENTLY_SHOP_URL%/}"/api/v1/products

PHP

<?php
declare(strict_types=1);

$baseUrl = rtrim(getenv('SHOPENTLY_SHOP_URL') ?: '', '/');
$origin = parse_url($baseUrl);
if (!$origin || ($origin['scheme'] ?? '') !== 'https' || empty($origin['host']) ||
    isset($origin['user'], $origin['pass']) || isset($origin['user']) || isset($origin['path']) ||
    isset($origin['query']) || isset($origin['fragment'])) {
    throw new RuntimeException('SHOPENTLY_SHOP_URL must be an HTTPS origin');
}
$credential = getenv('SHOPENTLY_ACCESS_TOKEN') ?: '';
if ($credential === '' || strpbrk($credential, "\r\n") !== false) {
    throw new RuntimeException('Invalid credential');
}
$headers = ['Idempotency-Key: example-create_product_api_v1_products_post', 'Content-Type: application/json'];
$headers[] = 'Authorization: Bearer ' . $credential;
$responseHeaders = [];
$handle = curl_init($baseUrl . '/api/v1/products');
curl_setopt_array($handle, [
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_SSL_VERIFYHOST => 2,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HEADERFUNCTION => static function ($handle, string $line) use (&$responseHeaders): int {
        if (str_contains($line, ':')) {
            [$name, $value] = explode(':', $line, 2);
            $responseHeaders[strtolower(trim($name))] = trim($value);
        }
        return strlen($line);
    },
]);
curl_setopt($handle, CURLOPT_POSTFIELDS, '{
  "name": "Example",
  "sku": "example"
}');
$raw = curl_exec($handle);
$status = curl_getinfo($handle, CURLINFO_RESPONSE_CODE);
$error = curl_error($handle);
curl_close($handle);
if ($raw === false) {
    throw new RuntimeException('Transport error: ' . $error);
}
if ($status < 200 || $status >= 300) {
    throw new RuntimeException('HTTP ' . $status . '; request_id=' .
        ($responseHeaders['x-request-id'] ?? '') . '; retry_after=' . ($responseHeaders['retry-after'] ?? ''));
}
$result = $raw === '' ? null : json_decode($raw, true, 512, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING);
echo json_encode($result, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE), PHP_EOL;

Python

from contextlib import ExitStack
import json
import os
from urllib.parse import urlsplit

import requests  # python -m pip install requests

base_url = os.environ["SHOPENTLY_SHOP_URL"].rstrip("/")
origin = urlsplit(base_url)
if origin.scheme != "https" or not origin.hostname or origin.username or origin.password or origin.path or origin.query or origin.fragment:
    raise ValueError("SHOPENTLY_SHOP_URL must be an HTTPS origin")
credential = os.environ['SHOPENTLY_ACCESS_TOKEN']
if not credential or "\r" in credential or "\n" in credential:
    raise ValueError("Invalid credential")
headers = {'Idempotency-Key': 'example-create_product_api_v1_products_post'}
headers["Authorization"] = 'Bearer' + " " + credential
body = '{\n  "name": "Example",\n  "sku": "example"\n}'
if body is not None:
    headers["Content-Type"] = "application/json"

with ExitStack() as stack:
    session = stack.enter_context(requests.Session())
    files = None
    if False:
        image = stack.enter_context(open(os.environ["SHOPENTLY_IMAGE_FILE"], "rb"))
        if os.fstat(image.fileno()).st_size > 5242880:
            raise ValueError("Image exceeds 5 MiB")
        files = {"file": ("article.png", image, "image/png")}
    response = session.request(
        'POST', base_url + '/api/v1/products', headers=headers,
        data=body.encode("utf-8") if body is not None else None, files=files,
        timeout=(5, 30), allow_redirects=False,
    )
    if not 200 <= response.status_code < 300:
        raise RuntimeError(f"HTTP {response.status_code}; request_id={response.headers.get('X-Request-ID', '')}; retry_after={response.headers.get('Retry-After', '')}")
    if False:
        if response.headers.get("Content-Type") != "image/webp" or len(response.content) > 5242880:
            raise ValueError("Unexpected image response")
        with open(os.environ["SHOPENTLY_OUTPUT_FILE"], "xb") as output:
            output.write(response.content)
    else:
        result = response.json() if response.content else None
        print(json.dumps(result, ensure_ascii=False, indent=2))

回應示例 201

JSON
{
  "data": {
    "deleted": false,
    "id": "example",
    "version": 1
  },
  "meta": {
    "request_id": "example"
  }
}

工作原理

  • 整合可以讀取所有未刪除的產品,包括草稿,但不包括被方案限制阻止的產品。
  • 被阻止的產品不出現在清單中;直接存取回傳 entitlements.resource_blocked。
  • 因此,產品在 API 中的可見性不同於店面發佈狀態。
  • 使用品牌、分類、屬性和媒體的現有識別碼。
  • 價格包含明確的幣種、價格表、稅務模式和並行控制版本。
  • 產品定價與變體定價相互獨立;請使用支援的價格結構及精確的十進位字串。

參數

查詢參數

locale字串 null選填

本次請求選擇的語言。

字串:minLength: 2maxLength: 20
market_id字串 null選填

上下文端點回傳的市場識別碼。

約束 · 字串 1
pattern
"^[a-z0-9][a-z0-9_-]{0,62}$"
market_code字串 null選填

上下文端點回傳的市場代碼。

字串:minLength: 1maxLength: 16

請求標頭

Idempotency-Key字串必填

單個邏輯寫入操作的唯一識別碼。

minLength: 1maxLength: 128
約束
pattern
"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$"
示例: "example-create_product_api_v1_products_post"

請求本文

application/json · 必填

ProductCreate
brand_id字串 null選填

品牌識別碼。

字串:minLength: 1maxLength: 63
condition字串選填

產品狀況。

約束
enum
["new", "refurbished", "used", "returned", "display", "damaged"]
預設值: "new"
description字串 null選填

所選語言的描述。

字串:maxLength: 100000
feature_value_ids陣列 <字串> 選填

所選屬性值的識別碼。

maxItems: 1000
陣列:minLength: 1maxLength: 63
identifiersProductIdentifiers null選填

產品識別代碼。

market_ids陣列 <字串> 選填

所選市場的識別碼。

maxItems: 1000
陣列:minLength: 1maxLength: 63
media_ids陣列 <字串> 選填

已存在媒體資產的識別碼。

maxItems: 20
陣列:minLength: 1maxLength: 63
meta_description字串 null選填

所選語言的搜尋引擎描述。

字串:maxLength: 160
meta_keywords陣列 <字串> null選填

所選語言的搜尋引擎關鍵詞。

陣列:maxItems: 20
陣列 / 陣列:maxLength: 50
meta_title字串 null選填

所選語言的搜尋引擎標題。

字串:maxLength: 70
name字串必填

對應上下文中的資源名稱。

minLength: 1maxLength: 300
示例: "Example"
pricingProductPrice 選填

價格配置及其並行控制版本。

primary_category_id字串 null選填

主要分類識別碼。

字串:minLength: 1maxLength: 63
published布林值選填

資源是否已發佈。

預設值: false
sku字串必填

庫存單位代碼。

minLength: 1maxLength: 100
約束
pattern
"^\\S+$"
示例: "example"
slug字串 null選填

所選語言的 URL 路徑段。

字串:maxLength: 160
tax_category_id字串 null選填

稅務類別識別碼。

字串:minLength: 1maxLength: 63
variant_value_ids陣列 <字串> 選填

所選變體值的識別碼。

maxItems: 250
陣列:minLength: 1maxLength: 63
variants_enabled布林值選填

產品是否使用變體。

預設值: false

回應

回應 201

dataMutationData 必填

成功回應的資料。

欄位 · data
deleted布林值必填

是否已執行刪除。

id字串必填

資源識別碼;請保留回傳的原值。

version整數 null必填

用於並行控制的資源版本。

metaContextPageMeta ContextMeta PageMeta RequestMeta 必填

回應元資料。

欄位 · meta

ContextPageMeta

locale字串必填

本次請求選擇的語言。

market_code字串必填

上下文端點回傳的市場代碼。

market_id字串必填

上下文端點回傳的市場識別碼。

paginationPagination 必填

遊標分頁元資料。

request_id字串必填

申請識別碼;在回應元資料中表示 HTTP 請求識別碼。

minLength: 1maxLength: 100

ContextMeta

locale字串必填

本次請求選擇的語言。

market_code字串必填

上下文端點回傳的市場代碼。

market_id字串必填

上下文端點回傳的市場識別碼。

request_id字串必填

申請識別碼;在回應元資料中表示 HTTP 請求識別碼。

minLength: 1maxLength: 100

PageMeta

paginationPagination 必填

遊標分頁元資料。

request_id字串必填

申請識別碼;在回應元資料中表示 HTTP 請求識別碼。

minLength: 1maxLength: 100

RequestMeta

request_id字串必填

申請識別碼;在回應元資料中表示 HTTP 請求識別碼。

minLength: 1maxLength: 100
回應示例

HTTP 狀態

201
資源已建立 架構
400
無效請求
401
需要身分驗證
403
權限不足
404
找不到資源
409
版本衝突
422
驗證失敗
429
超出請求限制
其他 HTTP 狀態 (7)
405
不允許的方法
413
請求過大
415
不支援的格式
500
伺服器錯誤
502
API 閘道錯誤
503
服務無法使用
504
閘道逾時

錯誤目錄: ErrorResponse

請求標頭與回應標頭

201

Location字串選填

已建立資源的相對 URL。

401

WWW-Authenticate字串選填

伺服器要求的身份驗證方案。

405

Allow字串選填

此資源支援的 HTTP 方法。

429, 503

Retry-After整數選填

重試前最少等待的秒數。

minimum: 0