Aqbeż għall-kontenut
ShopentlyLearn

Aġġorna · Stokk — Stokk

Ibdel id-data speċifikata f’“Stokk”. L-oqsma obbligatorji u r-regoli tal-kitba huma deskritti hawn taħt.

PATCH/api/v1/inventory/stock/{stock_id}

Awtentikazzjoni
Bearer
Disponibbli minn
STANDARD
Permessi meħtieġa
inventory.stock:update

Eżempji ta’ kodiċi

Eżempju ta’ talba

cURL

: "${SHOPENTLY_SHOP_URL:?}"

curl --disable --globoff --fail-with-body --silent --show-error \
  --proto '=https' --connect-timeout 5 --max-time 30 \
  --request PATCH \
  --header "Authorization: Bearer ${SHOPENTLY_ACCESS_TOKEN:?}" \
  --header 'Idempotency-Key: example-update_stock_api_v1_inventory_stock__stock_id__patch' \
  --header 'Content-Type: application/json' \
  --data-raw '{
  "expected_version": 1,
  "locations": [
    {
      "location_id": "example",
      "on_hand": 1
    }
  ],
  "reason": "Example"
}' \
  --url "${SHOPENTLY_SHOP_URL%/}"/api/v1/inventory/stock/stock_v1_WyJleGFtcGxlIiwicHJvZHVjdCIsImV4YW1wbGUiXQ

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-update_stock_api_v1_inventory_stock__stock_id__patch', 'Content-Type: application/json'];
$headers[] = 'Authorization: Bearer ' . $credential;
$responseHeaders = [];
$handle = curl_init($baseUrl . '/api/v1/inventory/stock/stock_v1_WyJleGFtcGxlIiwicHJvZHVjdCIsImV4YW1wbGUiXQ');
curl_setopt_array($handle, [
    CURLOPT_CUSTOMREQUEST => 'PATCH',
    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, '{
  "expected_version": 1,
  "locations": [
    {
      "location_id": "example",
      "on_hand": 1
    }
  ],
  "reason": "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-update_stock_api_v1_inventory_stock__stock_id__patch'}
headers["Authorization"] = 'Bearer' + " " + credential
body = '{\n  "expected_version": 1,\n  "locations": [\n    {\n      "location_id": "example",\n      "on_hand": 1\n    }\n  ],\n  "reason": "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(
        'PATCH', base_url + '/api/v1/inventory/stock/stock_v1_WyJleGFtcGxlIiwicHJvZHVjdCIsImV4YW1wbGUiXQ', 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))

Eżempju ta’ tweġiba 200

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

Kif jaħdem

  • Ir-rekords jiddistingwu l-kwantità fiżika on_hand, ir-riżervi tal-ordnijiet, ir-riżervi manwali u l-kwantità disponibbli għall-bejgħ.
  • Uża l-identifikatur u l-verżjoni tal-istokk mogħtija; l-istokk tal-prodott u tal-varjant huma miri separati.
  • sellable_limit ta’ -1 ifisser bla limitu, filwaqt li 0 ifisser li m’hemmx bejgħ disponibbli.
  • Disponibbiltà bla limitu tidher bħala null f’available.
  • Tittrattax null bħala żero.
  • Aġġustamenti tal-istokk, limiti tal-bejgħ u riżervi manwali jużaw operazzjonijiet u permessi separati.

Parametri

Parametri tal-mogħdija

stock_idStringObbligatorju

Identifikatur tar-rekord tal-istokk.

minLength: 1maxLength: 256
Eżempju: "stock_v1_WyJleGFtcGxlIiwicHJvZHVjdCIsImV4YW1wbGUiXQ"

Intestaturi tat-talba

Idempotency-KeyStringObbligatorju

Identifikatur uniku għal operazzjoni loġika waħda ta’ kitba.

minLength: 1maxLength: 128
Restrizzjonijiet
pattern
"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$"
Eżempju: "example-update_stock_api_v1_inventory_stock__stock_id__patch"

Kontenut tat-talba

application/json · Obbligatorju

StockAdjustmentUpdate
expected_versionNumru sħiħObbligatorju

Verżjoni li nqrat qabel il-kitba; nuqqas ta’ qbil jirrifjuta l-aġġornament.

minimum: 1maximum: 9223372036854775807
Eżempju: 1
locationsArray <LocationQuantity > Obbligatorju

Postijiet fil-maħżen.

minItems: 1maxItems: 100
Eżempju: [{"location_id":"example","on_hand":1}]
reasonStringObbligatorju

Raġuni rreġistrata għall-bidla.

minLength: 1maxLength: 500
Eżempju: "Example"

Tweġibiet

Risposta 200

dataMutationData Obbligatorju

Data ta’ tweġiba ta’ suċċess.

Oqsma · data
deletedBooleanObbligatorju

Jekk it-tħassir ġiex applikat.

idStringObbligatorju

Identifikatur tar-riżorsa; żommu kif mogħti.

versionNumru sħiħ nullObbligatorju

Verżjoni tar-riżorsa għall-kontroll tal-konkorrenza.

metaContextPageMeta ContextMeta PageMeta RequestMeta Obbligatorju

Metadata tat-tweġiba.

Oqsma · meta

ContextPageMeta

localeStringObbligatorju

Lingwa magħżula għal din it-talba.

market_codeStringObbligatorju

Kodiċi tas-suq mogħti mill-endpoint tal-kuntest.

market_idStringObbligatorju

Identifikatur tas-suq mogħti mill-endpoint tal-kuntest.

paginationPagination Obbligatorju

Metadata tal-paġinazzjoni bil-cursor.

request_idStringObbligatorju

Identifikatur tat-talba; fil-metadata tat-tweġiba jidentifika t-talba HTTP.

minLength: 1maxLength: 100

ContextMeta

localeStringObbligatorju

Lingwa magħżula għal din it-talba.

market_codeStringObbligatorju

Kodiċi tas-suq mogħti mill-endpoint tal-kuntest.

market_idStringObbligatorju

Identifikatur tas-suq mogħti mill-endpoint tal-kuntest.

request_idStringObbligatorju

Identifikatur tat-talba; fil-metadata tat-tweġiba jidentifika t-talba HTTP.

minLength: 1maxLength: 100

PageMeta

paginationPagination Obbligatorju

Metadata tal-paġinazzjoni bil-cursor.

request_idStringObbligatorju

Identifikatur tat-talba; fil-metadata tat-tweġiba jidentifika t-talba HTTP.

minLength: 1maxLength: 100

RequestMeta

request_idStringObbligatorju

Identifikatur tat-talba; fil-metadata tat-tweġiba jidentifika t-talba HTTP.

minLength: 1maxLength: 100
Eżempju ta’ tweġiba

Status HTTP

200
Risposta b’suċċess Skema
400
Talba mhux valida
401
Awtentikazzjoni meħtieġa
403
Permess miċħud
404
Riżorsa ma nstabitx
409
Kunflitt tal-verżjoni
422
Validazzjoni falliet
429
Inqabeż il-limitu tat-talbiet
Stati HTTP oħra (7)
405
Metodu mhux permess
413
Talba kbira wisq
415
Format mhux appoġġjat
500
Żball tas-server
502
Żball tal-gateway tal-API
503
Servizz mhux disponibbli
504
Skada l-ħin ta’ stennija

Katalgu tal-iżbalji: ErrorResponse

Headers

401

WWW-AuthenticateStringMhux obbligatorju

Skema ta’ awtentikazzjoni meħtieġa mis-server.

405

AllowStringMhux obbligatorju

Metodi HTTP appoġġati minn din ir-riżorsa.

429, 503

Retry-AfterNumru sħiħMhux obbligatorju

Dewmien minimu qabel tentattiv ieħor, f’sekondi.

minimum: 0