AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Integrating the PixVerse REST API: Automated Video Generation, Asset Uploads, and Asynchronous Task Polling

최지향 · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

Clicking buttons on a web UI is fine for creative prototyping. For an automated video production business, it is a complete non-starter. If your product relies on scheduled social media pipelines, algorithmic ad variation, or personalized video rendering at scale, the browser interface of PixVerse is an operational dead end. You need programmatic automation.

PixVerse exposes its video generation models through the OpenAPI v2 REST architecture. At 365Finds, we evaluate this API as one of the most accessible programmatic video engines currently available. But simplicity on paper hides specific integration landmines: custom tracing headers that break if reused, a rigid asset upload separation, and the complete lack of push webhooks, which forces you to build an asynchronous polling state machine.

Here is the exact architectural blueprint to integrate PixVerse REST API into an industrial-grade backend pipeline without human intervention.


1. Authentication and Header Conventions

PixVerse operates two regional base URLs. Global workloads route to:

https://app-api.pixverse.ai

For deployments physically located within mainland China requiring local network compliance, route requests to:

https://app-api.pixverseai.cn

Every single HTTP request sent to PixVerse OpenAPI v2 requires two mandatory headers:

  1. API-KEY: Your secret developer token generated from the PixVerse Platform console (https://platform.pixverse.ai).
  2. Ai-trace-id: A freshly generated UUIDv4 string.
API-KEY: YOUR_PLATFORM_API_KEY
Ai-trace-id: c9a0b12e-4b67-4d92-8871-3375d86f0011
Content-Type: application/json

The Ai-trace-id Trap

Most backend developers instinctively treat tracing headers like Stripe idempotency keys—caching a UUID across retry loops. Doing that with PixVerse will corrupt your telemetry or cause request anomalies. Ai-trace-id is purely a distributed request tracing handle. You must generate a brand new UUID for every single outbound HTTP request, including every single polling tick. At 365Finds, our testing showed that hardcoding or reusing Ai-trace-id across poll requests degrades debugging observability when an upstream task stalls.


2. Pre-Flight Asset Upload Pipelines

You cannot embed raw base64 data inside PixVerse generation payloads. Before dispatching an image-to-video or reference-guided task, source media must be ingested into PixVerse storage to obtain platform asset identifiers (img_id or media_id).

PixVerse strictly separates image assets from audio/video containers across two distinct endpoints.

Uploading Reference Images (/openapi/v2/image/upload)

Use multipart/form-data to submit reference keyframes. The file must be JPEG, PNG, or WebP format, capped at 20 MB and no larger than 10,000 pixels in any dimension. Alternatively, pass a publicly accessible image_url.

curl --location 'https://app-api.pixverse.ai/openapi/v2/image/upload' \
  --header 'API-KEY: YOUR_PLATFORM_API_KEY' \
  --header 'Ai-trace-id: 3c8e4d2a-89a1-4328-b0a3-f8a49c6b71f0' \
  --form 'image=@"/local/assets/character_master.png"'

Successful responses return an internal img_id:

{
  "ErrCode": 0,
  "ErrMsg": "success",
  "Resp": {
    "img_id": 8492039182371,
    "img_url": "https://cdn.pixverse.ai/upload/image/sample.png"
  }
}

Uploading Video and Audio Containers (/openapi/v2/media/upload)

If you are running video-to-video stylization, background video references, or audio lip-sync pipelines, post your media through the media upload endpoint:

ParameterTypeValid Formats / Constraints
mediaBinary FileMP4, MOV, WEBM for video; MP3, WAV, M4A, AAC for audio
media_urlStringAlternative publicly reachable media URL

This call returns Resp.media_id. Storing img_id and media_id separately in your worker task context prevents invalid type casting during downstream payload compilation.


3. Orchestrating Generation Payloads

Once asset IDs are secured, your orchestrator triggers task dispatch. The response is instantaneous and purely acknowledgment-based; the server checks parameter syntax, debits quota, and queues GPU rendering.

Text-to-Video Task Submission

POST /openapi/v2/video/text/generate HTTP/1.1
Host: app-api.pixverse.ai
API-KEY: YOUR_PLATFORM_API_KEY
Ai-trace-id: 11eb31a8-9d41-4c17-915f-f06b453e1a02
Content-Type: application/json

{
  "prompt": "Cinematic aerial tracking shot over dense misty redwood forest at dawn, anamorphic lens flare, photorealistic 8k",
  "negative_prompt": "blurry, distortion, low frame rate, cartoon, watermark",
  "model": "v6-max",
  "duration": 5,
  "quality": "720p",
  "aspect_ratio": "16:9",
  "seed": 0
}

Image-to-Video Task Submission

When animating static concept art or e-commerce products, pass the previously obtained img_id:

POST /openapi/v2/video/img/generate HTTP/1.1
Host: app-api.pixverse.ai
API-KEY: YOUR_PLATFORM_API_KEY
Ai-trace-id: d76f0b44-93c2-401d-8ff4-6ce5cb0272c8
Content-Type: application/json

{
  "img_id": 8492039182371,
  "prompt": "Camera pushes forward slowly as atmospheric dust particles float in sunlight",
  "model": "v6",
  "duration": 5,
  "quality": "720p"
}

Both endpoints return identical envelope signatures upon queuing:

{
  "ErrCode": 0,
  "ErrMsg": "success",
  "Resp": {
    "video_id": 1000000000000008,
    "credits": 5
  }
}

ErrCode: 0 does not mean the video is rendered. It only confirms the task was accepted. The integer video_id is your state tracker.


4. Designing the Asynchronous Polling State Machine

Because PixVerse v2 does not send webhooks, your integration layer must poll GET /openapi/v2/video/result/{video_id}.

Never block user-facing HTTP request threads with while-loops. 365Finds strongly advises running this inside a dedicated asynchronous worker queue (such as Celery, BullMQ, or Temporal).

GET /openapi/v2/video/result/1000000000000008 HTTP/1.1
Host: app-api.pixverse.ai
API-KEY: YOUR_PLATFORM_API_KEY
Ai-trace-id: 62bc7b99-a93e-4fa4-a820-e7178bfd885a

Task Status Codes

The polling engine must branch explicitly across four documented statuses:

Status CodeMeaningOperational Action
5Generating / In ProgressTask remains queued or actively rendering. Continue polling every 3–5 seconds with backoff.
1Generation CompletedSuccess. Extract Resp.url and trigger video ingest to private cloud storage.
7Moderation FailedPrompt or asset violated content filters. Abort immediately. Do not retry automatically.
8Generation FailedRendering engine failure or compute crash. Flag task and route to automated retry queue.
flowchart TD
    A[Submit Task: Text/Img Generate] --> B[Obtain video_id & ErrCode: 0]
    B --> C[Sleep 4s with Jitter]
    C --> D[Poll GET /openapi/v2/video/result/{video_id} with new Ai-trace-id]
    D --> E{Check Status}
    E -- status: 5 --> F{Exceeded 300s Timeout?}
    F -- No --> C
    F -- Yes --> G[Timeout Failure & Alert]
    E -- status: 1 --> H[Extract Resp.url & Download to Object Storage]
    E -- status: 7 --> I[Content Moderation Rejection: Mark Task Dead]
    E -- status: 8 --> J[Render Failed: Trigger Retry Queue]

Response Envelope for Finished Render (status: 1)

{
  "ErrCode": 0,
  "ErrMsg": "success",
  "Resp": {
    "status": 1,
    "video_id": 1000000000000008,
    "url": "https://media.pixverse.ai/generation/2026/render_output_1000000000000008.mp4",
    "duration": 5,
    "quality": "720p"
  }
}

5. Industrial Integration: Resilient Python Worker Pattern

The implementation below demonstrates a clean worker loop with dynamic trace ID generation, status dispatching, and automated cloud sync.

import os
import time
import uuid
import requests

PIXVERSE_BASE_URL = os.getenv("PIXVERSE_BASE_URL", "https://app-api.pixverse.ai")
API_KEY = os.environ["PIXVERSE_API_KEY"]

def build_headers() -> dict:
    return {
        "API-KEY": API_KEY,
        "Ai-trace-id": str(uuid.uuid4()),
        "Content-Type": "application/json"
    }

def submit_text_to_video(prompt: str, model: str = "v6-max") -> int:
    url = f"{PIXVERSE_BASE_URL}/openapi/v2/video/text/generate"
    payload = {
        "prompt": prompt,
        "model": model,
        "duration": 5,
        "quality": "720p",
        "aspect_ratio": "16:9"
    }
    
    response = requests.post(url, headers=build_headers(), json=payload, timeout=15)
    response.raise_for_status()
    data = response.json()
    
    if data.get("ErrCode") != 0:
        raise RuntimeError(f"Task dispatch rejected: {data.get('ErrMsg')}")
        
    return data["Resp"]["video_id"]

def poll_video_pipeline(video_id: int, max_wait_sec: int = 300, interval_sec: int = 4) -> str:
    url = f"{PIXVERSE_BASE_URL}/openapi/v2/video/result/{video_id}"
    start_time = time.monotonic()
    
    while time.monotonic() - start_time < max_wait_sec:
        # Every poll MUST pass a freshly minted Ai-trace-id
        headers = {
            "API-KEY": API_KEY,
            "Ai-trace-id": str(uuid.uuid4())
        }
        res = requests.get(url, headers=headers, timeout=15)
        res.raise_for_status()
        payload = res.json()
        
        if payload.get("ErrCode") != 0:
            raise RuntimeError(f"Poll query failed with ErrCode: {payload.get('ErrMsg')}")
            
        task_info = payload.get("Resp", {})
        status = task_info.get("status")
        
        if status == 1:
            return task_info["url"]
        elif status == 5:
            time.sleep(interval_sec)
            continue
        elif status == 7:
            raise ValueError(f"Video {video_id} rejected by PixVerse safety moderation.")
        elif status == 8:
            raise RuntimeError(f"Video {video_id} failed during diffusion/rendering.")
        else:
            time.sleep(interval_sec)
            
    raise TimeoutError(f"Video generation for ID {video_id} timed out after {max_wait_sec} seconds.")

6. Production Edge Cases and Operational Checklist

365Finds recommends enforcing three architectural safeguards before deploying to production:

  1. CDN Expiration & Direct Ingestion: PixVerse CDN output URLs should be treated as ephemeral download channels. As soon as your poller receives status: 1, stream the MP4 payload directly to your own Amazon S3 or Google Cloud Storage bucket. Storing raw PixVerse CDN URLs in client-facing databases leads to broken video links once CDN tokens expire.
  2. Moderation Circuit Breakers: Status 7 indicates a content moderation strike. Re-submitting the exact same prompt will fail repeatedly and waste team compute cycles. Store the flagged prompt string and prevent automated retries until a human operator reviews the safety flags.
  3. Avoid Serverless Blocking: Do not run long-polling loops inside stateless edge functions with short execution windows (such as standard Vercel or Cloudflare Worker endpoints). Video generation takes between 30 and 120 seconds depending on server load. Decouple submission from polling via background workers.

In PixVerse OpenAPI v2, video generation succeeds or fails cleanly on these exact status transitions. Manage your trace IDs, separate your asset uploads, poll via asynchronous message queues, and your automated video pipeline will run reliably around the clock.

References