# PixGT Open API > PixGT enterprise Open API: asynchronous tasks for e-commerce product suites, image generation and video generation. API keys are issued by enterprise admins in Enterprise admin panel → Developer / API; calls consume the enterprise's shared points. ## Overview The PixGT Open API lets your ERP, PIM, listing tool or in-house agent call PixGT's e-commerce visual generation directly: **product suites, image generation and video generation**. - **An enterprise feature**: API keys are issued by enterprise owners / admins in the enterprise admin panel. Calls consume the enterprise's **shared points** at the same price as the web app. - **One asynchronous task model**: every capability is created with `POST /tasks`; results come from polling `GET /tasks/{task_id}` or from webhooks. - **Safe retries**: task creation supports `Idempotency-Key`, so network retries never double-charge. - **Discoverable capabilities**: models, product suite modules, marketplaces and platform size presets are all available from the API, so nothing needs to be hard-coded. ### Environments | Environment | Base URL | Key prefix | | :--- | :--- | :--- | | Preview (sandbox) | `https://tapi.pixgt.com/open/v1` | `pgk_test_` | | Production | `https://api.pixgt.com/open/v1` | `pgk_live_` | - Integrate against the **sandbox** first; the interactive console on this site defaults to it. - The global edition (pixgt.com) and the China edition are separate systems; keys do not work across them. ### Conventions - Requests and responses use `application/json; charset=utf-8` (asset uploads use `multipart/form-data`); all fields are `snake_case`. - Timestamps are ISO 8601 UTC, e.g. `2026-11-28T15:00:00Z`. - Every response includes `X-Request-Id`; share it with support to locate a request quickly. - Billing is in **points**. ### For AI coding tools Give any of these links to Cursor, Claude Code or similar tools so they understand the whole API and can generate integration code: - [llms.txt](https://docs.pixgt.com/llms.txt): documentation index - [llms-full.txt](https://docs.pixgt.com/llms-full.txt): all guides plus every endpoint as Markdown - [openapi.yaml](https://docs.pixgt.com/openapi.yaml) / [openapi.json](https://docs.pixgt.com/openapi.json): machine-readable OpenAPI 3.1 specification ## Quickstart Generate your first **product suite** with `curl` in about five minutes: upload a product photo → estimate the price → create a task (with an idempotency key) → poll or receive a webhook → download the results. ### Before you start 1. **Get an API key**: an enterprise owner or admin signs in to PixGT and opens **Enterprise admin panel → Developer / API**, then clicks "Create key". Create integration keys in the **preview (sandbox) environment**; they start with `pgk_test_`. Production keys start with `pgk_live_`. See [Authentication & API keys](#authentication-api-keys). 2. **Pick an environment**: | Environment | Base URL | Notes | | :--- | :--- | :--- | | Preview (sandbox) | `https://tapi.pixgt.com/open/v1` | Separate database and keys. Integrate here first | | Production | `https://api.pixgt.com/open/v1` | Live environment, consumes your enterprise points | 3. Export two environment variables (used by every command below): ```bash export PIXGT_API_KEY="pgk_test_xxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" export PIXGT_BASE="https://tapi.pixgt.com/open/v1" ``` > The interactive console on this site defaults to the **sandbox**. Paste your key and click "Send" to call the API directly. Your key only travels between your browser and PixGT servers; no third-party proxy is involved. ### Step 1: Upload a product photo ```bash curl -s "$PIXGT_BASE/assets" \ -H "Authorization: Bearer $PIXGT_API_KEY" \ -F file=@./sku-10086.jpg ``` Returns `201`: ```json { "id": "asset_01JDQ8Z3K7M2V9X4R6T1B5N8C0", "object": "asset", "mime_type": "image/jpeg", "width": 1600, "height": 1600, "bytes": 834221, "expires_at": "2026-12-28T15:00:00Z" } ``` - png / jpg / jpeg / webp, up to 20 MB each. Assets are deleted automatically after **30 days**. - You can also skip the upload and pass a public `https` image URL in the task (see [Tasks & statuses](#tasks-statuses)). ### Step 2 (optional): Discover options Modules, platforms, text languages, festival themes and platform size presets are all available from the API. Do not hard-code them: ```bash curl -s "$PIXGT_BASE/options/product-suite" -H "Authorization: Bearer $PIXGT_API_KEY" curl -s "$PIXGT_BASE/models?type=image" -H "Authorization: Bearer $PIXGT_API_KEY" ``` ### Step 3: Estimate the price (free) ```bash curl -s "$PIXGT_BASE/tasks/estimate" \ -H "Authorization: Bearer $PIXGT_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "type": "product_suite", "input": { "images": [{ "asset_id": "asset_01JDQ8Z3K7M2V9X4R6T1B5N8C0" }], "product_description": "Portable blender bottle, 350 ml, USB-C charging", "platform": "amazon", "language": "en", "modules": ["main_image", "selling_points", "scene", "spec"], "size": { "preset_id": "amz_main" }, "model": "auto" } }' ``` Response: ```json { "object": "estimate", "type": "product_suite", "points": 480, "balance": 160000, "balance_after": 159520, "affordable": true, "breakdown": [{ "item": "main_image", "points": 120 }, { "item": "selling_points", "points": 120 }, { "item": "scene", "points": 120 }, { "item": "spec", "points": 120 }] } ``` > Point values in examples are illustrative; always rely on the live response. Estimates and actual charges use the same pricing function. ### Step 4: Create the task (with an idempotency key) ```bash curl -s -i "$PIXGT_BASE/tasks" \ -H "Authorization: Bearer $PIXGT_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: sku-10086-suite-v1" \ -d '{ "type": "product_suite", "input": { "images": [{ "asset_id": "asset_01JDQ8Z3K7M2V9X4R6T1B5N8C0" }], "product_description": "Portable blender bottle, 350 ml, USB-C charging", "platform": "amazon", "language": "en", "modules": ["main_image", "selling_points", "scene", "spec"], "size": { "preset_id": "amz_main" }, "model": "auto" }, "webhook_url": "https://erp.example.com/pixgt/callback", "client_reference_id": "SKU-10086" }' ``` Returns `202 Accepted` immediately (it does not wait for generation): ```json { "id": "task_01JDQ8Z3K7M2V9X4R6T1B5N8C0", "object": "task", "type": "product_suite", "status": "queued", "created_at": "2026-11-28T15:00:00Z", "cost": { "points_estimated": 480, "points_charged": 480, "points_refunded": 0 }, "client_reference_id": "SKU-10086" } ``` - Points are **pre-charged at creation** based on the estimate; failed outputs are refunded automatically. - When retrying after a network timeout, **reuse the same `Idempotency-Key`**: no duplicate task, no double charge (see [Idempotency](#idempotency)). ### Step 5: Get the result **Option A: polling** (interval ≥ 5 seconds) ```bash TASK_ID="task_01JDQ8Z3K7M2V9X4R6T1B5N8C0" while true; do RESP=$(curl -s "$PIXGT_BASE/tasks/$TASK_ID" -H "Authorization: Bearer $PIXGT_API_KEY") STATUS=$(echo "$RESP" | jq -r .status) echo "status=$STATUS" case "$STATUS" in succeeded|partially_succeeded|failed) break;; esac sleep 5 done echo "$RESP" | jq '.outputs[] | {module, status, url, url_expires_at}' ``` **Option B: webhook**: when the task reaches a final status, PixGT POSTs a `task.succeeded` / `task.partially_succeeded` / `task.failed` event to `webhook_url` (or your enterprise default URL). Its `data` is identical to the `GET /tasks/{task_id}` response. Always verify the signature; see [Webhooks](#webhooks). ### Step 6: Download and store `outputs[].url` is a **signed, temporary URL (valid for about 24 hours)**. Download the files **right after the task succeeds** and store them in your own storage; do not put PixGT URLs directly on product pages. If a URL expires, call `GET /tasks/{task_id}` again for a fresh one. See [Result URL expiry](#result-url-expiry). ```bash echo "$RESP" | jq -r '.outputs[] | select(.status=="succeeded") | "\(.index) \(.url)"' | while read -r IDX URL; do curl -s -o "output-$IDX.png" "$URL"; done ``` ### Next steps - Inputs for free-form image generation (`image_generation`) and video generation (`video_generation`) are described in [Tasks & statuses](#tasks-statuses). - Before going live, switch `PIXGT_BASE` to `https://api.pixgt.com/open/v1` and use a `pgk_live_` production key. - For AI coding tools: give `https://docs.pixgt.com/llms-full.txt` or `https://docs.pixgt.com/openapi.yaml` to Cursor, Claude Code or similar tools to generate integration code. ## Authentication & API keys Every endpoint uses **Bearer token** authentication: ```http Authorization: Bearer pgk_live_3fa9c0d1e2b4_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ``` ### Key format ```text pgk__<12 hex prefix>_<43 random characters> ``` | Prefix | Environment | Use | | :--- | :--- | :--- | | `pgk_test_` | Preview (sandbox) `https://tapi.pixgt.com/open/v1` | Integration and testing | | `pgk_live_` | Production `https://api.pixgt.com/open/v1` | Live traffic | - Sandbox and production are **separate systems** (separate databases and keys). Keys do not work across them. - The global edition (pixgt.com) and the China edition are also separate systems with separate keys. ### Where to create keys 1. An enterprise **owner** or **admin** signs in and opens **Enterprise admin panel → Developer / API** (regular members do not see this page). 2. Click "Create key" and fill in: - **Name** (required, e.g. "ERP production") and **note** (optional, e.g. "Shopify sync, contact: Alex"); - **Scopes** (all selected by default, see below); - **Expiry**: 90 days / 180 days / 1 year / never; - **Monthly budget** (optional): the maximum points this key may consume per month. Exceeding it returns `402 key_budget_exceeded`. 3. The new key appears in the list right away. > Phase one supports **enterprise keys** only: calls consume the enterprise's shared points and never touch any member's personal points. ### View and copy at any time - Keys are masked in the list (e.g. `pgk_live_3fa9c0d1e2b4••••••••••••Xq2Z`). - Click the **eye icon** to reveal the full key, or the **copy icon** to copy it directly. - Every reveal is audited (who, when, which key); the list shows "last viewed". ### If a key leaks: delete it - Delete a leaked or unused key from the list. It **stops working immediately**; requests using it return `401 invalid_api_key`. - Historical tasks and billing can still be traced to the deleted key. - **Rotation**: create a new key → switch your system to it → delete the old one. ### Scopes | Scope | Allowed endpoints | Default | | :--- | :--- | :---: | | `tasks:write` | `POST /tasks`, `POST /tasks/estimate` | ✅ | | `tasks:read` | `GET /tasks`, `GET /tasks/{task_id}` | ✅ | | `assets:write` | `POST /assets` | ✅ | | `account:read` | `GET /account`, `GET /account/balance` | ✅ | - `GET /models` and `GET /options/product-suite` only require a valid key, no specific scope. - A missing scope returns `403 insufficient_scope`. - A common pattern: one full-access key for the production system, and a read-only `account:read` key for a finance reconciliation script. ### Authentication errors | HTTP | `code` | Meaning | | :---: | :--- | :--- | | 401 | `missing_api_key` | No `Authorization` header | | 401 | `invalid_api_key` | Malformed, unknown or deleted key | | 401 | `api_key_expired` | The key has expired | | 403 | `insufficient_scope` | The key lacks the scope required by this endpoint | | 403 | `enterprise_expired` | The enterprise plan has expired (read-only period). Generation endpoints are blocked; read endpoints still work | | 403 | `api_access_disabled` | API access is not enabled for this enterprise, or it has been restricted by the platform | ### Security recommendations - **Store keys on your server only.** Never ship them in web front-ends, mini programs or mobile app bundles. - Do not commit keys to source control; use environment variables or a secrets manager. - Use a separate key per system and set monthly budgets to limit the blast radius. - The interactive console on this site calls the PixGT API straight from your browser (the API allows cross-origin requests) **without any third-party proxy**. We recommend using only sandbox `pgk_test_` keys in the console. ## Tasks & statuses All generation capabilities (product suite / image generation / video generation) are **asynchronous tasks** sharing the same endpoints and envelope; only `type` and `input` differ: ```text POST /tasks ──202──▶ GET /tasks/{task_id} (polling) or webhook (push) ``` ### Task types | `type` | Capability | Outputs | | :--- | :--- | :--- | | `product_suite` | Product suite: main image, selling points, scene and other e-commerce images in one task | 1 per module | | `image_generation` | Free-form image generation: prompt plus optional reference images | `n` images (1-4) | | `video_generation` | Video generation: prompt plus reference images / first frame / first and last frames | 1 video | > Future versions will add new `type` values (such as virtual try-on or background replacement). Clients must **tolerate unknown values**. ### Status machine ```text queued ──▶ processing ──┬─▶ succeeded (all outputs succeeded) │ ├─▶ partially_succeeded (some outputs failed; refunded) │ └─▶ failed (all failed; fully refunded) └──────────────────────▶ failed (moderation block / system error) ``` | `status` | Meaning | Final | | :--- | :--- | :---: | | `queued` | Accepted, points pre-charged, waiting to start | | | `processing` | Planning / generating | | | `succeeded` | All outputs succeeded | ✅ | | `partially_succeeded` | Finished; some outputs succeeded and some failed | ✅ | | `failed` | The task failed | ✅ | `partially_succeeded` mainly applies to **product suites** (several images per task): use the successful images right away and resubmit only the failed modules. ### Points: pre-charge and refunds The `cost` object: | Field | Meaning | | :--- | :--- | | `points_estimated` | Estimated points at creation (same as `POST /tasks/estimate`) | | `points_charged` | Points actually pre-charged at creation | | `points_refunded` | Points refunded for failed outputs | **Net cost = `points_charged` − `points_refunded`**. Example: a 4-image suite pre-charges 480 points; one image fails, so after completion `points_refunded = 120` and the net cost is 360 points. - Insufficient balance at creation returns `402 insufficient_balance`; an exhausted monthly key budget returns `402 key_budget_exceeded`. - API usage costs **the same** as generating inside the PixGT web app; there is no separate API pricing. ### Retrieve a task The `GET /tasks/{task_id}` response is **identical** to the `data` of a webhook event: ```json { "id": "task_01JDQ8Z3K7M2V9X4R6T1B5N8C0", "object": "task", "type": "product_suite", "status": "partially_succeeded", "progress": { "total": 4, "succeeded": 3, "failed": 1, "pending": 0 }, "input": { "...": "normalized echo of your input" }, "outputs": [ { "index": 0, "module": "main_image", "status": "succeeded", "url": "https://...signed URL...", "url_expires_at": "2026-11-29T15:00:00Z", "width": 2000, "height": 2000, "format": "png", "model": "seedream5.0" }, { "index": 3, "module": "spec", "status": "failed", "error": { "code": "content_policy_violation", "message": "The generated content did not pass the safety review", "retryable": false } } ], "cost": { "points_estimated": 480, "points_charged": 480, "points_refunded": 120 }, "error": null, "created_at": "2026-11-28T15:00:00Z", "completed_at": "2026-11-28T15:02:41Z", "client_reference_id": "SKU-10086", "metadata": { "shop": "amazon-us" }, "watermark": false } ``` - **Poll no more often than every 5 seconds.** Images usually take tens of seconds; videos may take several minutes. - Product suite `outputs` are always ordered `main_image` → `selling_points` → `scene` → `detail` → `spec` → `white_background` → `features` → `comparison` (only the modules you selected), regardless of the order in your `modules` array. - `outputs[].url` is a temporary signed URL; see [Result URL expiry](#result-url-expiry). - Video outputs also include `duration` (seconds) and `cover_url` (first-frame cover image). ### List tasks `GET /tasks?status=succeeded&type=product_suite&client_reference_id=SKU-10086&limit=20` - Returns only tasks **created through the API by the current enterprise**, newest first. - Cursor pagination: when `has_more=true`, pass the last item's `id` as `starting_after` for the next page. - `limit` is at most 100. Filter by `type`, `status`, `client_reference_id`, `created_after`, `created_before`. ### Common fields | Field | Required | Description | | :--- | :---: | :--- | | `type` | ✅ | `product_suite` / `image_generation` / `video_generation` | | `input` | ✅ | Type-specific parameters, see below | | `webhook_url` | | Overrides the enterprise default webhook URL; `https` only, ≤ 512 characters | | `client_reference_id` | | Your own business ID (≤ 64 characters); filterable in the task list | | `metadata` | | Up to 16 key/value pairs (keys ≤ 40 characters, string values ≤ 256 characters), echoed back and never used for generation | | `watermark` | | Defaults to `false`; see [Watermark](#watermark) | > **Strict validation**: any undefined field in the request body returns `400 invalid_parameter` (with `param` naming the field), so a misspelled field never silently does nothing. ### Image inputs `images[]` Each item is exactly one of: - `{ "asset_id": "asset_..." }`: returned by `POST /assets` (**recommended**, most reliable). - `{ "url": "https://..." }`: a public `https` URL that the server downloads and stores. Requirements: `https` only, no private/internal addresses, ≤ 20 MB, png / jpg / jpeg / webp, 15-second download timeout. Failures return `400 invalid_image_url` with `param` pointing at the item (e.g. `input.images[1].url`). ### `product_suite` | Field | Required | Description | | :--- | :---: | :--- | | `images` | ✅ | 1-6 product photos | | `product_description` | | Product name, selling points, extra notes (≤ 2000 characters) | | `platform` | | Target marketplace, values from `GET /options/product-suite` (e.g. `amazon`, `shopify`, `tiktok_shop`, `temu`, `shopee`) | | `language` | | Language of text in the images (ISO 639-1, e.g. `en`, `ja`, `de`) | | `modules` | ✅ | At least one, no duplicates: `main_image`, `selling_points`, `scene`, `detail`, `spec` (specifications), `white_background`, `features`, `comparison` | | `size` | | Unified size object; see [Size](#size) | | `model` | | Defaults to `auto`; values from `GET /models?type=image` | | `module_options.spec.product_size` | | Real product dimensions `{length, width, height, unit}` for the spec image; `unit` is `cm` / `mm` / `in`. Without it, the image shows dimension lines but no invented numbers | | `module_options.scene.hint` | | One-line scene description (≤ 60 characters) | | `module_options.comparison.mode` | | `ordinary` / `before_after` / `pain_point` | | `festival.theme` | | Festival / sales-event mood from `festival_themes`; `none` or omitted means none; `custom` requires `festival.custom {name ≤24, prompt ≤200, palette_id}` | ### `image_generation` ```json { "type": "image_generation", "input": { "prompt": "Place this perfume on a marble countertop in soft morning light", "images": [{ "asset_id": "asset_01JDQ8Z3K7M2V9X4R6T1B5N8C0" }], "n": 2, "size": { "width": 1200, "height": 1600 }, "model": "auto" } } ``` | Field | Required | Description | | :--- | :---: | :--- | | `prompt` | ✅ | Prompt, 1-4000 characters | | `images` | | Reference images, up to 10 (see the model's `max_input_images`) | | `n` | | Number of images, 1-4, default 1 | | `size` | | See [Size](#size) | | `model` | | Defaults to `auto`; available values from `GET /models?type=image` (e.g. `seedream5.0`) | ### `video_generation` ```json { "type": "video_generation", "input": { "prompt": "The camera slowly orbits the blender bottle as fruit drops in with a splash", "mode": "image_to_video", "images": [{ "asset_id": "asset_01JDQ8Z3K7M2V9X4R6T1B5N8C0" }], "model": "seedance2.0-fast", "duration": 5, "aspect_ratio": "9:16", "resolution": "720p" } } ``` | Field | Required | Description | | :--- | :---: | :--- | | `prompt` | ✅ | Video description, 1-4000 characters | | `model` | ✅ | Video model from `GET /models?type=video` | | `mode` | | `reference` (default, multi-image reference, 0-9 images) / `image_to_video` (first frame, exactly 1 image) / `first_last_frame` (first and last frames, exactly 2 images) | | `images` | | Count validated against `mode` | | `duration` | | Seconds; allowed values per the model's `durations` | | `aspect_ratio` | | `16:9` / `9:16` / `1:1` / `4:3` / `3:4` / `21:9` | | `resolution` | | `480p` / `720p` / `1080p` / `2k`, per model capabilities | | `enhance` | | Automatic upscaling (extra cost); not available for `1080p` / `2k` | ### Failure reasons inside a task Check `outputs[].error` for a single failed output and the top-level `error` for a failed task: | `code` | Meaning | Suggestion | | :--- | :--- | :--- | | `content_policy_violation` | Input or generated content failed the safety review | Change the prompt / images and resubmit | | `generation_failed` | Generation failed | Retryable | | `timeout` | Generation timed out | Retryable | | `watermark_failed` | Video watermarking failed | Retryable | | `internal_error` | System error | Retryable | Rely on the `retryable` flag: when `true`, you can resubmit the same request (with a **new** `Idempotency-Key`). ## Size Product suites and image generation describe the output size with **one** `size` object. Use **exactly one** of three forms, so resolution and aspect ratio can never be combined into a contradictory request. | Form | Example | Best for | | :--- | :--- | :--- | | Platform preset | `{ "preset_id": "amz_main" }` | **Recommended**: follow marketplace specs directly | | Exact pixels | `{ "width": 1000, "height": 1000 }` | Strict pixel requirements | | Tier + aspect ratio | `{ "tier": "2k", "aspect_ratio": "3:4" }` | You care about sharpness and framing only | Omitting `size` is equivalent to `{ "tier": "auto" }`; the model decides. ### 1. Platform preset `preset_id` Values come from `size_presets` in `GET /options/product-suite` (grouped by platform; each item has `width`, `height`, `aspect_ratio` and `module_group`). For example: | `preset_id` | Platform | Size | | :--- | :--- | :--- | | `amz_main` | Amazon main image | 2000 × 2000 | | `amz_main_1k` | Amazon main image | 1000 × 1000 | | `shopify_main` | Shopify | 2048 × 2048 | | `tts_main` | TikTok Shop | 1200 × 1200 | > These are examples only. Use the live list from the API and do not hard-code it. An unknown `preset_id` returns `400 invalid_parameter` (`param: input.size.preset_id`). A preset is effectively an exact pixel size and is billed the same way as exact pixels below. ### 2. Exact pixels `width` + `height` ```json { "size": { "width": 1200, "height": 1600 } } ``` - `width` and `height` must **both** be integers between **64 and 4096** pixels. - The aspect ratio must not exceed **3:1**. - **The billing tier is derived from the pixel size and is only ever lowered, never raised**: a 1000 × 1000 request is billed at the 1K tier, so you are never charged for 2K while receiving 1000 × 1000. ### 3. Tier + aspect ratio `tier` + `aspect_ratio` ```json { "size": { "tier": "2k", "aspect_ratio": "3:4" } } ``` - `tier`: `auto` / `1k` / `2k` / `4k`; defaults to `auto`. - `aspect_ratio`: `W:H` (e.g. `1:1`, `3:4`, `16:9`), not exceeding 3:1; omitted means the model decides. - Billing follows `tier`; unit prices are listed in `pricing` from `GET /models`. ### Common mistakes | Request | Result | | :--- | :--- | | `{ "preset_id": "amz_main", "tier": "2k" }` | `400`: only one form allowed | | `{ "width": 1000 }` | `400`: width and height are both required | | `{ "width": 4000, "height": 1000 }` | `400`: aspect ratio exceeds 3:1 | | `{ "tier": "8k" }` | `400`: tier must be auto / 1k / 2k / 4k | ### Videos do not use size Video tasks use the separate `aspect_ratio` and `resolution` fields (see [Tasks & statuses](#tasks-statuses)) and do not accept `size`. ## Watermark Available for all three task types, set at the **top level** of the request body (next to `type` and `input`): ```json { "type": "image_generation", "input": { "prompt": "..." }, "watermark": true } ``` | Value | Effect | | :--- | :--- | | omitted / `false` (default) | Outputs have **no watermark**. Most integrations that publish product images directly use this | | `true` | Outputs carry the platform watermark; useful for downstream review, previews or end-user trials | ### Rules - **No extra charge**: `true` and `false` cost the same. - The task object's `watermark` field echoes whether the task requested a watermark. - **Images**: the watermark is applied when the result URL is issued; nothing is regenerated and no time is added. - **Videos**: video watermarking is **not yet supported in the global region**. Sending `watermark: true` with a `video_generation` task returns `400 invalid_parameter` (`param: watermark`). - API tasks follow only the `watermark` parameter in the request and are not affected by any other watermark policy in the web app. ## Result URL expiry Task outputs' `outputs[].url` (and `cover_url` for videos) are **signed, temporary URLs** valid for about **24 hours**. The exact expiry time is in the sibling field `url_expires_at`. ```json { "index": 0, "status": "succeeded", "url": "https://.s3..amazonaws.com/.../20261127_ab12.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=...&X-Amz-Expires=86400&X-Amz-Signature=...", "url_expires_at": "2026-11-29T15:00:00Z" } ``` ### Why URLs expire 1. **Results live in a private bucket**: product images are confidential before launch and must not become permanent public links that anyone can open. 2. **Policy takedowns actually work**: links already handed out stop working at the latest when they expire, so removed content does not circulate forever. 3. **No hotlinking or bandwidth abuse**: permanent public links tend to be reused as free image hosting. ### How to use them - **Download right after the task succeeds and store the files in your own storage** (S3 / CDN / media library), then use your own URLs on product pages. - **Do not** put PixGT URLs on product pages or persist them as long-term references. - As long as the task is within its retention period, `GET /tasks/{task_id}` always returns a **fresh** URL. ### What a refreshed URL looks like The file itself (object path) **does not change**; only the signature parameters after `?` (signing time, lifetime, signature) do: ```text https://.s3..amazonaws.com/1234/output/images/20261127_ab12.png ?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=...&X-Amz-Date=20261128T160000Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=... ``` - Signatures are cached per time window: repeated queries within one window return **the same URL**, and a new one is issued in the next window. The remaining lifetime is therefore usually between 20 and 24 hours. **Always rely on `url_expires_at`** rather than assuming 24 hours. ### What an expired URL returns **HTTP 403** (not 404, no redirect) with the storage service's XML error body: ```xml AccessDenied Request has expired 86400 2026-11-28T15:00:00Z 2026-11-28T15:20:31Z ``` ### Standard handling Got **403** while downloading → call `GET /tasks/{task_id}` again for a fresh URL → download again. ```python import requests def download_output(base, api_key, task_id, index, path): for attempt in range(2): task = requests.get(f"{base}/tasks/{task_id}", headers={"Authorization": f"Bearer {api_key}"}, timeout=30).json() url = next(o["url"] for o in task["outputs"] if o["index"] == index) r = requests.get(url, timeout=120) if r.status_code == 403 and attempt == 0: continue # URL expired: fetch the task again for a fresh URL r.raise_for_status() with open(path, "wb") as f: f.write(r.content) return ``` ## Webhooks Webhooks do one thing: **notify you when an asynchronous task reaches a final status**. They are optional. Without them you can poll `GET /tasks/{task_id}` and get exactly the same result. Webhooks save you from writing polling loops, deliver results without polling delay, and eliminate a large number of status requests when processing many SKUs. ### Configuration - **Default webhook URL**: Enterprise admin panel → Developer / API → **Webhook settings**. Enter an `https` URL. Here you can also: - view / copy / reset the **signing secret** (`whsec_...`, with the same eye and copy icons); - "Send test event" (`webhook.test`); - review recent deliveries and redeliver manually. - **Per-task override**: pass `webhook_url` when creating a task; it takes precedence over the default URL. The same signing secret is used. - If neither is configured, nothing is delivered. ### Events | `type` | When | | :--- | :--- | | `task.succeeded` | All outputs of the task succeeded | | `task.partially_succeeded` | The task finished and some outputs failed (failed outputs refunded) | | `task.failed` | The task failed (fully refunded) | | `webhook.test` | Sent when you click "Send test event"; `data` is `{"message": "..."}`, not a task object | ### Delivery format ```http POST https://erp.example.com/pixgt/callback Content-Type: application/json User-Agent: PixGT-Webhook/1.0 PixGT-Event-Id: evt_01JDQ8Z3K7M2V9X4R6T1B5N8C0 PixGT-Signature: t=1764342161,v1=5f8c...e21 ``` ```json { "id": "evt_01JDQ8Z3K7M2V9X4R6T1B5N8C0", "object": "event", "type": "task.partially_succeeded", "created_at": "2026-11-28T15:02:41.000Z", "data": { "id": "task_01JDQ8Z3K7M2V9X4R6T1B5N8C0", "object": "task", "status": "partially_succeeded", "...": "identical to the GET /tasks/{task_id} response" } } ``` ### Signature verification ```text PixGT-Signature: t=,v1= v1 = HEX( HMAC_SHA256( key = the full signing secret string (including the whsec_ prefix), message = "{t}.{raw request body}" ) ) ``` Your endpoint must: 1. Compute the signature over the **raw request body bytes** (do not parse and re-serialize JSON; key order and whitespace would change); 2. Compare signatures in **constant time** (`timingSafeEqual` / `hmac.compare_digest` / `hash_equals`); 3. Reject requests where `|now − t| > 300 seconds` to prevent replays; 4. **Deduplicate** by `PixGT-Event-Id` (retries can deliver the same event more than once). #### Test vector Use this in your unit tests to validate your implementation: ```text secret: whsec_dGVzdF9zZWNyZXRfZm9yX2RvY3Nfb25seQ t: 1764342161 body: {"id":"evt_01JDQ8Z3K7M2V9X4R6T1B5N8C0","object":"event","type":"webhook.test","created_at":"2026-11-28T15:02:41.000Z","data":{"message":"This is a test event from PixGT Open API."}} signature: t=1764342161,v1=2da0b6011106a10126964289ad9e27e8c65ae0f9fd0212122e38173ae64d818f ``` (Freeze "now" to `t` in the test; otherwise the 300-second tolerance check fails.) #### Node.js (Express) ```js const crypto = require('crypto'); const express = require('express'); const SECRET = process.env.PIXGT_WEBHOOK_SECRET; // whsec_... function verifyPixgtSignature(rawBody, header, secret, toleranceSec = 300) { const parts = {}; for (const kv of String(header || '').split(',')) { const i = kv.indexOf('='); if (i > 0) parts[kv.slice(0, i).trim()] = kv.slice(i + 1).trim(); } const t = parseInt(parts.t, 10); if (!Number.isFinite(t) || !parts.v1) return false; if (Math.abs(Math.floor(Date.now() / 1000) - t) > toleranceSec) return false; const expected = crypto.createHmac('sha256', secret).update(`${t}.`).update(rawBody).digest('hex'); const a = Buffer.from(expected, 'hex'); const b = Buffer.from(parts.v1, 'hex'); return a.length === b.length && crypto.timingSafeEqual(a, b); } const app = express(); // You need the raw body: use express.raw, not express.json app.post('/pixgt/callback', express.raw({ type: 'application/json' }), (req, res) => { if (!verifyPixgtSignature(req.body, req.get('PixGT-Signature'), SECRET)) { return res.status(400).send('invalid signature'); } const event = JSON.parse(req.body.toString('utf8')); res.status(200).send('ok'); // acknowledge quickly with 2xx setImmediate(() => handleEvent(event)); // then process asynchronously (dedupe by event.id) }); ``` #### Python (Flask) ```python import hashlib import hmac import os import time from flask import Flask, request, abort SECRET = os.environ["PIXGT_WEBHOOK_SECRET"] # whsec_... app = Flask(__name__) def verify_pixgt_signature(raw_body: bytes, header: str, secret: str, tolerance: int = 300) -> bool: try: parts = dict(kv.strip().split("=", 1) for kv in (header or "").split(",")) t, v1 = int(parts["t"]), parts["v1"] except (KeyError, ValueError): return False if abs(int(time.time()) - t) > tolerance: return False expected = hmac.new(secret.encode("utf-8"), f"{t}.".encode("utf-8") + raw_body, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, v1) @app.post("/pixgt/callback") def pixgt_callback(): raw = request.get_data() # raw bytes if not verify_pixgt_signature(raw, request.headers.get("PixGT-Signature", ""), SECRET): abort(400) event = request.get_json(force=True) # dedupe by event["id"], then enqueue for processing return "ok", 200 ``` #### Java ```java import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; public final class PixgtWebhook { public static boolean verify(byte[] rawBody, String header, String secret) throws Exception { if (header == null) return false; String t = null, v1 = null; for (String kv : header.split(",")) { String[] p = kv.trim().split("=", 2); if (p.length != 2) continue; if (p[0].equals("t")) t = p[1]; else if (p[0].equals("v1")) v1 = p[1]; } if (t == null || v1 == null) return false; long ts; try { ts = Long.parseLong(t); } catch (NumberFormatException e) { return false; } if (Math.abs(System.currentTimeMillis() / 1000L - ts) > 300) return false; Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); mac.update((t + ".").getBytes(StandardCharsets.UTF_8)); byte[] digest = mac.doFinal(rawBody); StringBuilder hex = new StringBuilder(); for (byte b : digest) hex.append(String.format("%02x", b)); return MessageDigest.isEqual( hex.toString().getBytes(StandardCharsets.UTF_8), v1.toLowerCase().getBytes(StandardCharsets.UTF_8)); } } ``` In Spring Boot, read the raw body with `@RequestBody byte[] body`. #### PHP ```php $tolerance) return false; $expected = hash_hmac('sha256', $parts['t'] . '.' . $rawBody, $secret); return hash_equals($expected, strtolower($parts['v1'])); } $raw = file_get_contents('php://input'); // raw request body $sig = $_SERVER['HTTP_PIXGT_SIGNATURE'] ?? ''; if (!pixgt_verify_signature($raw, $sig, getenv('PIXGT_WEBHOOK_SECRET'))) { http_response_code(400); exit('invalid signature'); } $event = json_decode($raw, true); // dedupe by $event['id'], then process http_response_code(200); echo 'ok'; ``` ### Delivery and retries - Any **2xx** response counts as delivered; the **timeout is 10 seconds**. Return 2xx first and process asynchronously. - On failure (non-2xx, timeout, connection error) PixGT retries after **1 min / 5 min / 30 min / 2 h / 6 h / 12 h / 24 h**, for **at most 8 attempts including the first**. - `webhook.test` events are delivered once and never retried. - Delivery history and manual redelivery are available in the admin panel. - Webhooks are **notifications**, not the only channel: you can always fall back to `GET /tasks/{task_id}` (poll no more often than every 5 seconds). ## Idempotency After a network timeout you cannot know whether the request succeeded. **Retry with the same `Idempotency-Key`** and PixGT guarantees no duplicate task and no double charge. ```http POST /tasks Authorization: Bearer pgk_live_... Content-Type: application/json Idempotency-Key: sku-10086-suite-v1 ``` ### Rules | Situation | Result | | :--- | :--- | | First request | Created normally, returns `202` | | Within 24 hours, same API key + same `Idempotency-Key` + **same body** | Returns the originally created task (`202`) with header `Idempotent-Replayed: true`; **no extra charge** | | Same `Idempotency-Key` + **different body** | `409 idempotency_conflict` | | Same `Idempotency-Key` while the first request is still being processed | `409 idempotency_conflict`; retry later or query the task | - Applies to `POST /tasks` (create task). `POST /tasks/estimate` never charges and needs no idempotency key. - `Idempotency-Key` must be 1-64 characters, otherwise `400 invalid_parameter` (`param: Idempotency-Key`). - Scoped per **API key**: different keys using the same value do not interfere. - "Same body" is compared semantically as JSON; field order does not matter. ### How to choose a key Build it from **your own business identifiers** instead of generating a random value each time, so retries still match after a process restart: ```text sku-10086-suite-v1 # SKU + purpose + version order-20261128-0042-video # order number + type ``` To **intentionally** generate again for the same SKU, use a new key (e.g. `-v2`). ### Recommended retry policy | Response | Retry? | | :--- | :--- | | Network error / timeout / `500` / `503` | ✅ Exponential backoff, **same `Idempotency-Key`** | | `429` | ✅ Wait for `Retry-After`, then retry | | `409 idempotency_conflict` | Check `GET /tasks?client_reference_id=...` first to see whether the task exists | | Other `4xx` | ❌ Fix the request and send it again (with a new key) | ## Rate limits & concurrency ### Request rate (per API key) | Category | Endpoints | Default limit | | :--- | :--- | :--- | | Write | `POST /tasks`, `POST /tasks/estimate`, `POST /assets` | **60 requests / minute** | | Read | `GET /tasks`, `GET /tasks/{task_id}`, `GET /account`, `GET /account/balance`, etc. | **600 requests / minute** | | Invalid key attempts (per source IP) | Any | 30 requests / minute | - Exceeding a limit returns `429` with `error.code = rate_limit_exceeded` and a `Retry-After` header (seconds to wait). Wait that long before retrying. - Your key's limits are returned in `limits.requests_per_minute` from `GET /account`. - Poll tasks no more often than every **5 seconds**; for large batches use [Webhooks](#webhooks) to drastically cut status requests. ### Concurrent tasks (per enterprise) The number of **in-progress** (`queued` / `processing`) API tasks per enterprise is capped by plan: | Plan | Concurrent task limit | | :--- | :---: | | Starter | 10 | | Pro | 15 | | Flagship | 20 | | Custom | 30 (can be raised) | - API tasks and members' tasks in the web app are **counted separately**, so API batches never crowd out your team's day-to-day work. - Exceeding the cap returns `429` with `error.code = concurrency_limit_exceeded`; wait for some tasks to finish and resubmit. - The current cap is `limits.concurrent_tasks` in `GET /account`. ### Batch submission tips 1. Keep a submission queue in your system whose **concurrency stays below the cap**; 2. Send an `Idempotency-Key` and `client_reference_id` with every task; 3. On `429`, retry after `Retry-After` (or exponential backoff); do not resend immediately; 4. Receive results by webhook and refill the queue as tasks complete. ## Errors ### Error body Every error uses the same structure and comes with an `X-Request-Id` response header: ```json { "error": { "type": "invalid_request_error", "code": "invalid_parameter", "message": "input.modules must contain at least one module", "param": "input.modules", "request_id": "req_01JDQ8Z3K7M2V9X4R6T1B5N8C0" } } ``` | Field | Description | | :--- | :--- | | `type` | Error category | | `code` | **Stable error code. Branch on this only** | | `message` | Human-readable text; language follows `Accept-Language` (`zh` / `en`, English by default). Wording may change, so never parse it | | `param` | Path of the offending field (e.g. `input.images[1].url`), parameter errors only | | `request_id` | Unique request ID; include it when contacting support | ### Error codes | HTTP | `type` | `code` | Description | Retry | | :---: | :--- | :--- | :--- | :---: | | 400 | `invalid_request_error` | `invalid_parameter` | Validation failed (including unknown fields); see `param` | | | 400 | `invalid_request_error` | `invalid_image_url` | Image URL cannot be downloaded, is too large or has an unsupported format | | | 400 | `invalid_request_error` | `unsupported_task_type` | `type` does not exist or is not enabled for this enterprise | | | 400 | `invalid_request_error` | `model_unavailable` | Model does not exist or has been retired; see `GET /models` | | | 400 | `content_policy_error` | `content_policy_violation` | Prompt or input image failed the safety review | | | 401 | `authentication_error` | `missing_api_key` | No `Authorization` header | | | 401 | `authentication_error` | `invalid_api_key` | Invalid or deleted key | | | 401 | `authentication_error` | `api_key_expired` | The key has expired | | | 402 | `billing_error` | `insufficient_balance` | Not enough shared enterprise points | | | 402 | `billing_error` | `key_budget_exceeded` | The key's monthly budget is used up | | | 403 | `permission_error` | `insufficient_scope` | The key lacks the scope this endpoint requires | | | 403 | `permission_error` | `enterprise_expired` | Enterprise plan expired (read-only period); renew to keep generating | | | 403 | `permission_error` | `api_access_disabled` | API access not enabled, or the account is restricted | | | 404 | `invalid_request_error` | `resource_not_found` | Endpoint, task or asset not found, or not owned by this enterprise | | | 405 | `invalid_request_error` | `method_not_allowed` | Wrong HTTP method | | | 409 | `invalid_request_error` | `idempotency_conflict` | Idempotency key reused with a different body, or the same key is still in progress | | | 413 | `invalid_request_error` | `file_too_large` | Upload exceeds 20 MB | | | 415 | `invalid_request_error` | `unsupported_media_type` | Wrong body format: task creation requires `application/json`, uploads require `multipart/form-data` | | | 429 | `rate_limit_error` | `rate_limit_exceeded` | Too many requests; wait for `Retry-After` | ✅ | | 429 | `rate_limit_error` | `concurrency_limit_exceeded` | Too many tasks in progress | ✅ | | 500 | `api_error` | `internal_error` | Server error | ✅ | | 503 | `api_error` | `service_unavailable` | Maintenance or upstream temporarily unavailable | ✅ | > `api_key_revoked` in the specification is reserved; deleted keys currently return `invalid_api_key`. ### Errors inside tasks When a task that was already created fails during generation, there is no HTTP error. The failure appears in the task's `error` and `outputs[].error`; see "Failure reasons inside a task" in [Tasks & statuses](#tasks-statuses). ### Handling tips - Branch on `code`; use `message` only for display or logging. - Log the `X-Request-Id` of every request so support can locate it quickly. - Retry retryable errors with exponential backoff, reusing the same `Idempotency-Key` for task creation (see [Idempotency](#idempotency)). ## Changelog ### 1.0.0-draft (2026-11-28) First public draft. - Unified asynchronous task API: `POST /tasks`, `GET /tasks/{task_id}`, `GET /tasks`, supporting three task types: - `product_suite` - `image_generation` - `video_generation` - Price estimates with `POST /tasks/estimate` (free). - Asset upload with `POST /assets` (deleted automatically after 30 days). - Capability discovery with `GET /models` and `GET /options/product-suite`. - Account and balance with `GET /account` and `GET /account/balance`. - Final-status webhooks (`task.succeeded` / `task.partially_succeeded` / `task.failed`) signed with HMAC-SHA256. - `Idempotency-Key`, per-key rate limits and per-enterprise concurrency limits. - Unified `size` object (platform preset / exact pixels / tier + aspect ratio) and the `watermark` switch. ### Compatibility policy - Within `v1` we only make **backward-compatible** changes: new endpoints, new optional fields and new enum values (such as new task `type` values, error codes or event types). Make your code **tolerate unknown fields and unknown enum values**. - Breaking changes ship under a new major version path (e.g. `/open/v2`) with advance notice. ## API reference Base URLs: `https://tapi.pixgt.com/open/v1` (Global preview (sandbox, use pgk_test_ keys)); `https://api.pixgt.com/open/v1` (Global production (use pgk_live_ keys)) Authentication: `Authorization: Bearer ` ### Tasks Unified asynchronous generation tasks (product suite / image generation / video generation) #### POST /tasks **Create a generation task** · operationId `createTask` Requires scope `tasks:write`. Points are pre-charged at creation based on the estimate; failed outputs are refunded automatically. Returns `202` immediately; get the result by polling `GET /tasks/{task_id}` or via webhook. ##### Parameters | Name | In | Type | required | Description | | :--- | :--- | :--- | :---: | :--- | | `Idempotency-Key` | header | string | | ≤ 64 characters. Within 24 hours, the same key with the same request body returns the original result without charging again; a different body returns 409. maxLength: `64` | | `Accept-Language` | header | string | | Language of the error `message`: `zh` or `en` enum: `zh`, `en` | ##### Request body (required) Content-Type: `application/json` — `CreateTaskRequest` - oneOf [1] `CreateProductSuiteTask` - oneOf [2] `CreateImageGenerationTask` - oneOf [3] `CreateVideoGenerationTask` - discriminator: `type` (`product_suite` → `CreateProductSuiteTask`, `image_generation` → `CreateImageGenerationTask`, `video_generation` → `CreateVideoGenerationTask`) Examples: - productSuite (Product suite) ```json { "type": "product_suite", "input": { "images": [ { "asset_id": "asset_01JDQ8Z3K7M2V9X4R6T1B5N8C0" } ], "product_description": "Portable blender bottle, 350 ml, USB-C charging", "platform": "taobao", "language": "zh", "modules": [ "main_image", "selling_points", "scene", "spec" ], "size": { "preset_id": "tb_main" }, "model": "auto", "module_options": { "spec": { "product_size": { "length": 8, "width": 8, "height": 22, "unit": "cm" } }, "scene": { "hint": "On a picnic table at an outdoor campsite" } } }, "webhook_url": "https://erp.example.com/pixgt/callback", "client_reference_id": "SKU-10086" } ``` - imageGeneration (Image generation) ```json { "type": "image_generation", "input": { "prompt": "Place this perfume on a marble countertop in soft morning light", "images": [ { "url": "https://img.example.com/perfume.jpg" } ], "n": 2, "size": { "width": 1200, "height": 1600 } } } ``` - videoGeneration (Video generation) ```json { "type": "video_generation", "input": { "prompt": "The camera slowly orbits the blender bottle as fruit drops in with a splash", "mode": "image_to_video", "images": [ { "asset_id": "asset_01JDQ8Z3K7M2V9X4R6T1B5N8C0" } ], "model": "seedance2.0-fast", "duration": 5, "aspect_ratio": "9:16", "resolution": "720p" } } ``` ##### Responses - **202** Task accepted — `application/json` `Task` — headers: `X-Request-Id`, `Idempotent-Replayed` - **400** Invalid parameters / content policy violation / model unavailable — `application/json` `ErrorResponse` - **401** Authentication failed — `application/json` `ErrorResponse` - **402** Insufficient balance or the key's monthly budget is used up — `application/json` `ErrorResponse` - **403** Insufficient scope / enterprise expired (read-only) / API access not enabled — `application/json` `ErrorResponse` - **409** Idempotency key conflict — `application/json` `ErrorResponse` - **415** Wrong body format (task creation requires application/json, uploads require multipart/form-data) — `application/json` `ErrorResponse` - **429** Rate limit or concurrency limit exceeded — `application/json` `ErrorResponse` — headers: `Retry-After` - **500** Server error; safe to retry — `application/json` `ErrorResponse` #### GET /tasks **List tasks** · operationId `listTasks` Requires scope `tasks:read`. Returns only tasks created through the Open API by the current enterprise, newest first. ##### Parameters | Name | In | Type | required | Description | | :--- | :--- | :--- | :---: | :--- | | `type` | query | `TaskType` | | | | `status` | query | `TaskStatus` | | | | `client_reference_id` | query | string | | maxLength: `64` | | `created_after` | query | string (date-time) | | | | `created_before` | query | string (date-time) | | | | `limit` | query | integer | | default: `20`; minimum: `1`; maximum: `100` | | `starting_after` | query | string | | Cursor: pass the `id` of the last item on the previous page | ##### Responses - **200** OK — `application/json` object - `object` (const `"list"`, required) - `data` (array<`Task`>, required) - `has_more` (boolean, required) - **401** Authentication failed — `application/json` `ErrorResponse` - **403** Insufficient scope / enterprise expired (read-only) / API access not enabled — `application/json` `ErrorResponse` - **429** Rate limit or concurrency limit exceeded — `application/json` `ErrorResponse` — headers: `Retry-After` #### POST /tasks/estimate **Estimate price** · operationId `estimateTask` Requires scope `tasks:write`. Same input as task creation; nothing is charged and no task is created. Uses the same pricing function as actual billing. ##### Request body (required) Content-Type: `application/json` — `CreateTaskRequest` - oneOf [1] `CreateProductSuiteTask` - oneOf [2] `CreateImageGenerationTask` - oneOf [3] `CreateVideoGenerationTask` - discriminator: `type` (`product_suite` → `CreateProductSuiteTask`, `image_generation` → `CreateImageGenerationTask`, `video_generation` → `CreateVideoGenerationTask`) ##### Responses - **200** OK — `application/json` `Estimate` - **400** Invalid parameters / content policy violation / model unavailable — `application/json` `ErrorResponse` - **401** Authentication failed — `application/json` `ErrorResponse` - **403** Insufficient scope / enterprise expired (read-only) / API access not enabled — `application/json` `ErrorResponse` - **429** Rate limit or concurrency limit exceeded — `application/json` `ErrorResponse` — headers: `Retry-After` #### GET /tasks/{task_id} **Retrieve a task** · operationId `getTask` Requires scope `tasks:read`. The response is identical to the `data` of webhook events. Poll no more often than every 5 seconds. ##### Parameters | Name | In | Type | required | Description | | :--- | :--- | :--- | :---: | :--- | | `task_id` | path | string | ✅ | pattern: `^task_[0-9A-HJKMNP-TV-Z]{26}$` | ##### Responses - **200** OK — `application/json` `Task` - **401** Authentication failed — `application/json` `ErrorResponse` - **403** Insufficient scope / enterprise expired (read-only) / API access not enabled — `application/json` `ErrorResponse` - **404** Resource not found or not owned by this enterprise — `application/json` `ErrorResponse` - **429** Rate limit or concurrency limit exceeded — `application/json` `ErrorResponse` — headers: `Retry-After` ### Assets Input asset upload #### POST /assets **Upload an image asset** · operationId `uploadAsset` Requires scope `assets:write`. Assets are deleted automatically after 30 days. ##### Request body (required) Content-Type: `multipart/form-data` — object - `file` (string (binary), required) — png / jpg / jpeg / webp, ≤ 20 MB - `purpose` (string) [enum: `input`; default: `"input"`] ##### Responses - **201** Uploaded — `application/json` `Asset` — headers: `X-Request-Id` - **400** Invalid parameters / content policy violation / model unavailable — `application/json` `ErrorResponse` - **401** Authentication failed — `application/json` `ErrorResponse` - **403** Insufficient scope / enterprise expired (read-only) / API access not enabled — `application/json` `ErrorResponse` - **413** File too large — `application/json` `ErrorResponse` - **429** Rate limit or concurrency limit exceeded — `application/json` `ErrorResponse` — headers: `Retry-After` ### Catalog Discover models, capabilities and options #### GET /models **Available models, capabilities and prices** · operationId `listModels` Values are generated live by the server; retired models are not listed. ##### Parameters | Name | In | Type | required | Description | | :--- | :--- | :--- | :---: | :--- | | `type` | query | string | | enum: `image`, `video` | ##### Responses - **200** OK — `application/json` object - `object` (const `"list"`, required) - `data` (array<`Model`>, required) - **401** Authentication failed — `application/json` `ErrorResponse` #### GET /options/product-suite **Product suite options** · operationId `getProductSuiteOptions` Modules, marketplaces, text languages, festival themes and platform size presets. Same source as the options in the web app. ##### Responses - **200** OK — `application/json` `ProductSuiteOptions` - **401** Authentication failed — `application/json` `ErrorResponse` ### Account Enterprise account, balance and current key information #### GET /account **Enterprise and current key information** · operationId `getAccount` Requires scope `account:read`. ##### Responses - **200** OK — `application/json` `Account` - **401** Authentication failed — `application/json` `ErrorResponse` - **403** Insufficient scope / enterprise expired (read-only) / API access not enabled — `application/json` `ErrorResponse` #### GET /account/balance **Shared points balance** · operationId `getBalance` Requires scope `account:read`. ##### Responses - **200** OK — `application/json` `Balance` - **401** Authentication failed — `application/json` `ErrorResponse` - **403** Insufficient scope / enterprise expired (read-only) / API access not enabled — `application/json` `ErrorResponse` ## Webhook events ### POST (webhook) taskEvent **Task final-status event** · operationId `onTaskEvent` Event types: `task.succeeded` / `task.partially_succeeded` / `task.failed`. Signature: `PixGT-Signature: t=,v1=`, `v1 = HMAC_SHA256(whsec_secret, "{t}.{raw request body}")`. Receivers should compare signatures in constant time, reject requests where |now − t| > 300s, and deduplicate by `PixGT-Event-Id`. Any 2xx counts as success; failures are retried with 1m/5m/30m/2h/6h/12h/24h backoff, at most 8 attempts. #### Parameters | Name | In | Type | required | Description | | :--- | :--- | :--- | :---: | :--- | | `PixGT-Event-Id` | header | string | ✅ | | | `PixGT-Signature` | header | string | ✅ | | #### Request body (required) Content-Type: `application/json` — `WebhookEvent` - `id` (string, required) [examples: `evt_01JDQ8Z3K7M2V9X4R6T1B5N8C0`] - `object` (const `"event"`) - `type` (string, required) [enum: `task.succeeded`, `task.partially_succeeded`, `task.failed`, `webhook.test`] - `created_at` (string (date-time), required) - `data` (oneOf(`Task` | object), required) — For task.* events this is the task object (same shape as GET /tasks/{task_id}); for webhook.test it is { message } - oneOf [1] `Task` - oneOf [2] **option 2** - `message` (string, required) #### Responses - **200** Received ## Schemas ### TaskType New values will be added in future versions (such as try_on, background_replace); clients must tolerate unknown values. Type: string [enum: `product_suite`, `image_generation`, `video_generation`] ### TaskStatus Type: string [enum: `queued`, `processing`, `succeeded`, `partially_succeeded`, `failed`] ### ImageInput Exactly one of: `asset_id` (recommended) or a public `https` URL (downloaded and stored by the server; private addresses are rejected) - oneOf [1] **option 1** - `asset_id` (string, required) [pattern: `^asset_[0-9A-HJKMNP-TV-Z]{26}$`] - (no additional properties allowed) - oneOf [2] **option 2** - `url` (string (uri), required) [pattern: `^https://`] - (no additional properties allowed) ### Size Use exactly one of three forms, so resolution and aspect ratio can never be combined into a contradictory request. - oneOf [1] **Preset** - `preset_id` (string, required) — Platform size preset ID; see `/options/product-suite` - (no additional properties allowed) - oneOf [2] **Exact** - `width` (integer, required) — Aspect ratio must not exceed 3:1 [minimum: `64`; maximum: `4096`] - `height` (integer, required) [minimum: `64`; maximum: `4096`] - (no additional properties allowed) - oneOf [3] **TierRatio** - `tier` (string, required) [enum: `auto`, `1k`, `2k`, `4k`] - `aspect_ratio` (string) [examples: `1:1`, `3:4`, `16:9`] - (no additional properties allowed) ### ProductSuiteModule Type: string [enum: `main_image`, `selling_points`, `scene`, `detail`, `spec`, `white_background`, `features`, `comparison`] ### ProductSuiteInput - `images` (array<`ImageInput`>, required) [minItems: `1`; maxItems: `6`] - `product_description` (string) [maxLength: `2000`] - `platform` (string) — Target marketplace; values from `/options/product-suite` [examples: `amazon`, `taobao`, `pinduoduo`, `douyin`, `jd`, `temu`, `shopee`, `tiktok_shop`] - `language` (string) — Language of text in the images (ISO 639-1) [examples: `zh`, `en`, `ja`] - `modules` (array<`ProductSuiteModule`>, required) [minItems: `1`; uniqueItems] - `size` (`Size`) - `model` (string) [default: `"auto"`; examples: `auto`, `seedream5.0`, `gpt-image-2`, `nano-banana-pro`] - `module_options` (object) - `spec` (object) - `product_size` (object) - `length` (number) [exclusiveMinimum: `0`] - `width` (number) [exclusiveMinimum: `0`] - `height` (number) [exclusiveMinimum: `0`] - `unit` (string) [enum: `cm`, `mm`, `in`; default: `"cm"`] - (no additional properties allowed) - (no additional properties allowed) - `scene` (object) - `hint` (string) [maxLength: `60`] - (no additional properties allowed) - `comparison` (object) - `mode` (string) [enum: `ordinary`, `before_after`, `pain_point`] - (no additional properties allowed) - (no additional properties allowed) - `festival` (object) - `theme` (string) — Festival theme ID from festival_themes in `/options/product-suite`; `none` or omitted means no festival mood - `custom` (object) — Only allowed when theme=custom - `name` (string) [maxLength: `24`] - `prompt` (string) [maxLength: `200`] - `palette_id` (string) — See festival_palettes in `/options/product-suite` - (no additional properties allowed) - (no additional properties allowed) - (no additional properties allowed) ### ImageGenerationInput - `prompt` (string, required) [minLength: `1`; maxLength: `4000`] - `images` (array<`ImageInput`>) — Reference images [maxItems: `10`] - `n` (integer) [default: `1`; minimum: `1`; maximum: `4`] - `size` (`Size`) - `model` (string) [default: `"auto"`; examples: `auto`, `seedream5.0`, `gpt-image-2`, `nano-banana-pro`] - (no additional properties allowed) ### VideoGenerationInput - `prompt` (string, required) [minLength: `1`; maxLength: `4000`] - `mode` (string) [enum: `reference`, `image_to_video`, `first_last_frame`; default: `"reference"`] - `images` (array<`ImageInput`>) — reference mode: 0-9 images; image_to_video: exactly 1 (first frame); first_last_frame: exactly 2 (first frame, last frame) [maxItems: `9`] - `model` (string, required) — Values from `/models?type=video` - `duration` (integer) — Seconds; allowed values are listed in the model capabilities - `aspect_ratio` (string) [examples: `16:9`, `9:16`, `1:1`] - `resolution` (string) [examples: `480p`, `720p`, `1080p`, `2k`] - `enhance` (boolean) — Automatic upscaling, billed extra; not available for 1080p / 2k; cannot be combined with watermark [default: `false`] - (no additional properties allowed) ### CreateTaskRequest Task request discriminated by `type` (discriminated union) - oneOf [1] `CreateProductSuiteTask` - oneOf [2] `CreateImageGenerationTask` - oneOf [3] `CreateVideoGenerationTask` - discriminator: `type` (`product_suite` → `CreateProductSuiteTask`, `image_generation` → `CreateImageGenerationTask`, `video_generation` → `CreateVideoGenerationTask`) ### CreateProductSuiteTask - allOf → `TaskRequestCommon` - `type` (const `"product_suite"`, required) - `input` (`ProductSuiteInput`, required) ### CreateImageGenerationTask - allOf → `TaskRequestCommon` - `type` (const `"image_generation"`, required) - `input` (`ImageGenerationInput`, required) ### CreateVideoGenerationTask - allOf → `TaskRequestCommon` - `type` (const `"video_generation"`, required) - `input` (`VideoGenerationInput`, required) ### TaskRequestCommon - `watermark` (boolean) — No watermark by default; `true` adds the platform watermark at no extra cost. Video tasks reach a final status only after the watermark is burned in; video watermarks are not yet supported in the global region. [default: `false`] - `webhook_url` (string (uri)) [maxLength: `512`; pattern: `^https://`] - `client_reference_id` (string) [maxLength: `64`] - `metadata` (object) [maxProperties: `16`] - additionalProperties: string ### Cost - `points_estimated` (integer, required) - `points_charged` (integer, required) — Points actually pre-charged at creation - `points_refunded` (integer, required) — Points refunded for failed outputs; net cost = charged − refunded ### TaskError - `code` (string, required) [examples: `content_policy_violation`, `generation_failed`, `timeout`, `watermark_failed`, `internal_error`] - `message` (string, required) - `retryable` (boolean) ### TaskOutput - `index` (integer, required) - `module` (`ProductSuiteModule`) — product_suite only - `status` (string, required) [enum: `pending`, `succeeded`, `failed`] - `url` (string (uri)) — Signed URL, valid for 24 hours by default - `url_expires_at` (string (date-time)) - `cover_url` (string (uri)) — Video only: first-frame cover image - `width` (integer) - `height` (integer) - `duration` (number) — Video only: seconds - `format` (string) [examples: `png`, `jpg`, `mp4`] - `model` (string) - `error` (`TaskError`) ### Task - `id` (string, required) [examples: `task_01JDQ8Z3K7M2V9X4R6T1B5N8C0`] - `object` (const `"task"`, required) - `type` (`TaskType`, required) - `status` (`TaskStatus`, required) - `progress` (object) - `total` (integer) - `succeeded` (integer) - `failed` (integer) - `pending` (integer) - `input` (object) — Normalized echo of the input - `outputs` (array<`TaskOutput`>) - `cost` (`Cost`, required) - `error` (oneOf(`TaskError` | null)) - oneOf [1] `TaskError` - oneOf [2] **option 2** - `created_at` (string (date-time), required) - `completed_at` (string | null (date-time)) - `client_reference_id` (string | null) - `metadata` (object) - additionalProperties: string - `watermark` (boolean) — Whether this task requested a watermark ### Estimate - `object` (const `"estimate"`, required) - `type` (`TaskType`) - `points` (integer, required) - `balance` (integer) — Currently available points - `breakdown` (array) - `item` (string) - `points` (integer) - `balance_after` (integer) - `affordable` (boolean, required) ### Asset - `id` (string, required) [examples: `asset_01JDQ8Z3K7M2V9X4R6T1B5N8C0`] - `object` (const `"asset"`, required) - `mime_type` (string) - `width` (integer) - `height` (integer) - `bytes` (integer) - `expires_at` (string (date-time)) ### Model - `id` (string, required) - `object` (const `"model"`) - `type` (string, required) [enum: `image`, `video`] - `display_name` (object) - `zh` (string) - `en` (string) - `supported_task_types` (array<`TaskType`>) - `capabilities` (object) — Images: max_input_images / max_n / tiers / exact_size; videos: modes / durations / aspect_ratios / resolutions / enhance - `pricing` (object) — Images are billed per image (by tier), videos per second (by resolution) ### LabeledOption - `id` (string, required) - `label` (object, required) - `zh` (string) - `en` (string) ### ProductSuiteOptions - `modules` (array<`LabeledOption`>) - `platforms` (array<`LabeledOption`>) - `languages` (array<`LabeledOption`>) - `festival_themes` (array<`LabeledOption`>) - `festival_palettes` (array<`LabeledOption`>) - `size_presets` (object) — Grouped by platform ID - additionalProperties: array - allOf → `LabeledOption` - `module_group` (string) - `width` (integer) - `height` (integer) - `aspect_ratio` (string) ### Account - `object` (const `"account"`) - `owner_type` (string) [enum: `enterprise`, `user`] - `edition` (string) [enum: `cn`, `global`] - `user` (object) — Personal keys only - `id` (integer) - `enterprise` (object) - `id` (integer) - `name` (string) - `plan` (string) [enum: `starter`, `pro`, `flagship`, `custom`] - `status` (string) - `expires_at` (string (date-time)) - `read_only` (boolean) - `limits` (object) - `concurrent_tasks` (integer) — Enterprise keys only: maximum number of tasks in progress at the same time - `requests_per_minute` (object) - `write` (integer) - `read` (integer) - `api_key` (object) - `id` (string) - `name` (string) - `prefix` (string) - `monthly_budget` (integer | null) - `scopes` (array) - `expires_at` (string | null (date-time)) ### Balance - `object` (const `"balance"`) - `points` (object) - `total` (integer) - `remaining` (integer) - `used` (integer) - `frozen` (integer) — Points frozen after plan expiry; unfrozen on renewal (enterprise only) - `api_key_budget` (object | null) - `monthly_limit` (integer) - `used_this_month` (integer) - `resets_at` (string (date-time)) ### WebhookEvent - `id` (string, required) [examples: `evt_01JDQ8Z3K7M2V9X4R6T1B5N8C0`] - `object` (const `"event"`) - `type` (string, required) [enum: `task.succeeded`, `task.partially_succeeded`, `task.failed`, `webhook.test`] - `created_at` (string (date-time), required) - `data` (oneOf(`Task` | object), required) — For task.* events this is the task object (same shape as GET /tasks/{task_id}); for webhook.test it is { message } - oneOf [1] `Task` - oneOf [2] **option 2** - `message` (string, required) ### ErrorResponse - `error` (object, required) - `type` (string, required) [enum: `invalid_request_error`, `content_policy_error`, `authentication_error`, `billing_error`, `permission_error`, `rate_limit_error`, `api_error`] - `code` (string, required) [enum: `invalid_parameter`, `invalid_image_url`, `unsupported_task_type`, `model_unavailable`, `content_policy_violation`, `missing_api_key`, `invalid_api_key`, `api_key_expired`, `insufficient_balance`, `key_budget_exceeded`, `insufficient_scope`, `enterprise_expired`, `api_access_disabled`, `resource_not_found`, `method_not_allowed`, `idempotency_conflict`, `file_too_large`, `unsupported_media_type`, `rate_limit_exceeded`, `concurrency_limit_exceeded`, `internal_error`, `service_unavailable`] - `message` (string, required) - `param` (string) [examples: `input.modules`] - `request_id` (string) ## Security schemes - `bearerAuth`: http bearer (format `pgk_live_<12 hex>_<43 chars>`) — Issued by enterprise owners / admins in Enterprise admin panel → Developer / API; keys can be viewed and copied at any time. Use `pgk_test_` keys for the sandbox and `pgk_live_` keys for production. Store keys on your server only and delete a key immediately if it leaks.