AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Programmatic Video Generation with MiniMax Video API: Webhooks, Task Polling, and Pipeline Automation

심동규 · 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

Scaling video generation from individual prompt tests on the Hailuo AI web interface into an automated production line requires transitioning to programmatic APIs. For content platforms, dynamic advertising engines, and social marketing automation, generative video introduces unique backend constraints. Unlike text LLMs that return tokens within seconds, video diffusion models take between 40 seconds and several minutes to synthesize 5 to 6 seconds of photorealistic footage. Holding open a synchronous HTTP connection over that duration guarantees gateway timeouts, broken sockets, and wasted compute credits.

The MiniMax Video API solves this through an asynchronous, distributed execution model. Submitting a generation job yields an immediate task tracking ticket, leaving developers to resolve status updates either reactively via webhooks or proactively through status polling.

At 365Finds, our engineering assessment is unequivocal: for any commercial pipeline exceeding 100 video jobs daily, a hybrid webhook architecture with an active polling fallback is mandatory. Relying solely on polling wastes network bandwidth and risks hitting API rate limits, while relying solely on webhooks leaves jobs vulnerable to silent callback drops caused by network partitions or ingress proxy restarts.

This guide details the exact REST API specifications, authentication patterns, payload tuning, webhook challenge verification, polling state machines, and the critical 9-hour ephemeral asset retention lifecycle necessary to build an industrial-grade video synthesis pipeline.


1. Authentication and Base Endpoints

The MiniMax Video API uses standard Bearer token authentication via HTTP headers. API keys are provisioned within the MiniMax Open Platform console.

MiniMax operates two primary gateway environments depending on deployment geography:

All API requests must include the authorization header and declare JSON content:

Authorization: Bearer YOUR_MINIMAX_API_KEY
Content-Type: application/json

Requests lacking valid Bearer credentials return HTTP 401 Unauthorized with a structured error envelope in the response body.


2. Dispatching Video Generation Tasks (POST /v1/video_generation)

To launch a video rendering job, send a POST request to /v1/video_generation. The endpoint supports both Text-to-Video (T2V) and Image-to-Video (I2V) workflows.

Parameter Breakdown

ParameterTypeRequiredDescription and Engineering Guidance
modelstringYesModel identifier, such as MiniMax-Hailuo-2.3, MiniMax-H3, or video-01.
promptstringYesDescriptive prompt guiding scene action, lighting, camera movement, and aesthetic style.
first_frame_imagestringOptionalPublic HTTPS image URL or Base64 data URI (data:image/...). Required for Image-to-Video generation.
prompt_optimizerbooleanOptionalDefault true. When enabled, internal LLMs expand prompts for richer cinematography. 365Finds recommends setting this to false in strict brand-governed pipelines to prevent creative hallucination.
callback_urlstringOptionalPublic HTTPS webhook endpoint on your infrastructure where state changes will be pushed.
durationintegerOptionalLength of the output video in seconds (typically 5 or 6 seconds depending on model tier).
resolutionstringOptionalTarget output resolution, e.g., 720P, 1080P, or 2K.

Sample Dispatch Request: Image-to-Video with Webhook

curl -X POST "https://api.minimax.io/v1/video_generation" \
  -H "Authorization: Bearer $MINIMAX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "MiniMax-Hailuo-2.3",
    "prompt": "Cinematic slow push-in shot of the product on a rotating slate base, dramatic studio rim lighting, 4k commercial render",
    "first_frame_image": "https://assets.example.com/products/sku-9812/hero-render.jpg",
    "prompt_optimizer": false,
    "callback_url": "https://pipeline.example.com/api/v1/webhooks/minimax",
    "duration": 5,
    "resolution": "1080P"
  }'

Initial Synchronous Response

The API responds synchronously within 200–500ms, acknowledging task submission without waiting for video generation:

{
  "task_id": "184920485938176",
  "base_resp": {
    "status_code": 0,
    "status_msg": "success"
  }
}

Store this task_id immediately in your primary database or Redis task queue associated with your internal request ID.


3. Asynchronous Execution: Webhooks vs. Polling

Video generation takes between 40 and 180 seconds under standard queue loads. MiniMax provides two mechanisms to track progress: push notifications via callback_url and pull queries via /v1/query/video_generation.

+-------------------+                    +----------------------+                    +-----------------------+
|  Client Pipeline  |                    |  MiniMax Video API   |                    | Cloud Object Storage  |
+-------------------+                    +----------------------+                    +-----------------------+
          |                                         |                                            |
          |  1. POST /v1/video_generation          |                                            |
          |---------------------------------------->|                                            |
          |  2. Returns { task_id }                |                                            |
          |<----------------------------------------|                                            |
          |                                         |                                            |
          |-- [Challenge Handshake on setup] ------>|                                            |
          |<-- Echo { challenge } in < 3s ----------|                                            |
          |                                         |                                            |
          |                                         | (Async rendering queue: 40-180s)           |
          |                                         |                                            |
          |  3a. Webhook Push: status="Success"     |                                            |
          |<----------------------------------------|                                            |
          |   (OR 3b. Fallback Poll GET /query)     |                                            |
          |---------------------------------------->|                                            |
          |                                         |                                            |
          |  4. GET /v1/files/retrieve?file_id=... |                                            |
          |---------------------------------------->|                                            |
          |  5. Returns signed download_url (9h)    |                                            |
          |<----------------------------------------|                                            |
          |                                                                                      |
          |  6. Stream download bytes and persist immediately                                   |
          |------------------------------------------------------------------------------------->|
          |  7. S3 / R2 Object Key Confirmed                                                     |
          |<-------------------------------------------------------------------------------------|

Strategy A: Configuring Webhooks (callback_url)

Webhooks eliminate idle polling loops and provide instantaneous notifications upon render completion.

The 3-Second Challenge Handshake

When configuring an endpoint or registering a webhook callback, MiniMax performs an automated URL verification check. The verification request delivers a JSON payload containing a challenge parameter:

{
  "challenge": "b8f2d01c9ae4b4737"
}

Your server must respond with HTTP 200 within 3 seconds, returning the exact challenge string in the response body:

{
  "challenge": "b8f2d01c9ae4b4737"
}

Failure to echo the challenge within the 3-second window will cause MiniMax to mark the callback endpoint as unreachable, preventing subsequent event delivery.

Webhook Completion Payload

When generation completes or terminates in an error, MiniMax sends a POST request to your callback_url:

{
  "task_id": "184920485938176",
  "status": "Success",
  "file_id": "184921984712390",
  "video_width": 1920,
  "video_height": 1080,
  "base_resp": {
    "status_code": 0,
    "status_msg": "success"
  }
}

If generation fails (due to safety filters, corrupted input frames, or server timeouts), status returns "Fail" and base_resp.status_msg provides the failure diagnostic.


Strategy B: Polling via GET /v1/query/video_generation

When operating behind strict corporate firewalls, NAT networks without public ingress, or local development environments, polling is required.

Polling Request

curl -X GET "https://api.minimax.io/v1/query/video_generation?task_id=184920485938176" \
  -H "Authorization: Bearer $MINIMAX_API_KEY"

Task State Machine

The query endpoint transitions through five explicit lifecycle states:

[Preparing] ---> [Queueing] ---> [Processing] ---> [Success] (file_id present)
                                               ---> [Fail]    (status_msg diagnostic)
  1. Preparing: Task metadata validated; assets (such as first_frame_image) being fetched and pre-processed.
  2. Queueing: Job is queued in the GPU scheduler awaiting cluster capacity.
  3. Processing: Diffusion frames are actively rendering.
  4. Success: Rendering finished. Payload contains file_id, video_width, and video_height.
  5. Fail: Generation aborted or rejected by validation rules.

Polling Interval and Rate-Limit Safeguards

Do not poll aggressively. Polling faster than every 10 seconds provides no latency advantage and exhausts your API query quotas.

365Finds recommends the following polling profile:


4. The 9-Hour Ephemeral Download Link Trap

A critical architectural pitfall in naive integrations is treating the video URL returned by MiniMax as permanent storage.

When a task succeeds, MiniMax yields a file_id. To obtain the actual download URL, your pipeline calls the File Retrieval API:

curl -X GET "https://api.minimax.io/v1/files/retrieve?file_id=184921984712390" \
  -H "Authorization: Bearer $MINIMAX_API_KEY"

Response:

{
  "file": {
    "file_id": "184921984712390",
    "bytes": 6291456,
    "created_at": 1730502400,
    "filename": "output_aigc.mp4",
    "purpose": "video_generation",
    "download_url": "https://cdn.minimax.chat/..."
  },
  "base_resp": {
    "status_code": 0,
    "status_msg": "success"
  }
}

The Expiration Constraint

[!WARNING] The download_url provided by /v1/files/retrieve is a temporary signed URL with an expiration window of 9 hours. After 9 hours, the link returns HTTP 403/404, and the file cannot be downloaded using that URL.

If your web application saves this download_url directly into your client-facing database, video playback will break across your entire platform the following day.

Automated Cloud Ingestion Rule

A production pipeline must treat persistent cloud upload as an atomic, non-negotiable step of job resolution:

  1. Receive task success via Webhook or Polling.
  2. Call /v1/files/retrieve with file_id to fetch the active download_url.
  3. Stream the raw MP4 stream directly into your company's private cloud bucket (Amazon S3, Cloudflare R2, or Alibaba Cloud OSS).
  4. Persist your private bucket key or proprietary CDN URL into your database.
  5. Only then dispatch downstream notifications (e.g., notifying editing suites or marking marketing jobs complete).

5. End-to-End Implementation Blueprint (Python & FastAPI)

Below is an enterprise-ready pipeline implementation combining task creation, webhook processing with challenge verification, fallback status polling, and immediate transfer to Amazon S3.

import os
import time
import requests
import boto3
from fastapi import FastAPI, Request, Response, status
from pydantic import BaseModel

MINIMAX_API_KEY = os.getenv("MINIMAX_API_KEY")
MINIMAX_BASE_URL = "https://api.minimax.io"
S3_BUCKET_NAME = os.getenv("S3_BUCKET_NAME")

s3_client = boto3.client("s3")
app = FastAPI()

HEADERS = {
    "Authorization": f"Bearer {MINIMAX_API_KEY}",
    "Content-Type": "application/json"
}

def dispatch_video_task(prompt: str, first_frame_url: str = None, callback_url: str = None) -> str:
    """Submit a video generation job to MiniMax Video API."""
    payload = {
        "model": "MiniMax-Hailuo-2.3",
        "prompt": prompt,
        "prompt_optimizer": False,  # Strict prompt compliance for automated pipelines
        "duration": 5,
        "resolution": "1080P"
    }
    if first_frame_url:
        payload["first_frame_image"] = first_frame_url
    if callback_url:
        payload["callback_url"] = callback_url

    response = requests.post(f"{MINIMAX_BASE_URL}/v1/video_generation", headers=HEADERS, json=payload, timeout=10)
    response.raise_for_status()
    data = response.json()
    
    if data.get("base_resp", {}).get("status_code") != 0:
        raise RuntimeError(f"MiniMax API Error: {data.get('base_resp', {}).get('status_msg')}")
        
    return data["task_id"]

def transfer_to_s3(file_id: str, destination_s3_key: str) -> str:
    """Resolve ephemeral download URL and transfer MP4 to private S3 bucket."""
    # 1. Fetch ephemeral download URL
    res = requests.get(
        f"{MINIMAX_BASE_URL}/v1/files/retrieve",
        headers=HEADERS,
        params={"file_id": file_id},
        timeout=10
    )
    res.raise_for_status()
    file_meta = res.json().get("file", {})
    download_url = file_meta.get("download_url")
    
    if not download_url:
        raise ValueError("Missing download_url in file retrieve response")

    # 2. Stream video stream directly into S3
    with requests.get(download_url, stream=True, timeout=60) as video_stream:
        video_stream.raise_for_status()
        s3_client.upload_fileobj(video_stream.raw, S3_BUCKET_NAME, destination_s3_key)
        
    return f"https://{S3_BUCKET_NAME}.s3.amazonaws.com/{destination_s3_key}"

@app.post("/api/v1/webhooks/minimax")
async def handle_minimax_webhook(request: Request):
    """Handle challenge verification and task completion webhooks."""
    body = await request.json()

    # Step 1: Handle MiniMax 3-second challenge handshake
    if "challenge" in body:
        return {"challenge": body["challenge"]}

    task_id = body.get("task_id")
    task_status = body.get("status")

    if task_status == "Success":
        file_id = body.get("file_id")
        s3_key = f"generated_videos/{task_id}.mp4"
        permanent_url = transfer_to_s3(file_id, s3_key)
        print(f"[PIPELINE SUCCESS] Task {task_id} archived to {permanent_url}")
        # Update database record: status='completed', s3_url=permanent_url
    elif task_status == "Fail":
        err_msg = body.get("base_resp", {}).get("status_msg", "Unknown error")
        print(f"[PIPELINE FAILED] Task {task_id} failed: {err_msg}")
        # Update database record: status='failed', error=err_msg

    return {"status": "received"}

def poll_task_with_fallback(task_id: str, max_wait_sec: int = 600) -> str:
    """Fallback polling worker for offline or dead-letter recovery."""
    start_time = time.time()
    time.sleep(30)  # Initial render grace delay

    while time.time() - start_time < max_wait_sec:
        res = requests.get(
            f"{MINIMAX_BASE_URL}/v1/query/video_generation",
            headers=HEADERS,
            params={"task_id": task_id},
            timeout=10
        )
        if res.status_code == 200:
            data = res.json()
            task_status = data.get("status")
            if task_status == "Success":
                file_id = data.get("file_id")
                return transfer_to_s3(file_id, f"generated_videos/{task_id}.mp4")
            elif task_status == "Fail":
                raise RuntimeError(f"Task {task_id} failed: {data.get('base_resp', {}).get('status_msg')}")
        elif res.status_code == 429:
            time.sleep(20)  # Rate limit cooldown
            
        time.sleep(15)

    raise TimeoutError(f"Task {task_id} exceeded maximum polling timeout")

6. Pipeline Resilience and Production Guardrails

Building a high-volume automated rendering engine requires implementing safeguards around distributed failure modes:

  1. Idempotency via task_id Deduping: Webhooks guarantee at-least-once delivery. Network retries may send identical completion events multiple times. Use Redis locks (SET task:{task_id} "locked" EX 60 NX) or unique constraints on database task records to ensure your pipeline does not trigger duplicate S3 uploads or downstream rendering charges.
  2. Dead-Letter Recovery Timers: Webhooks can be lost during infrastructure deployments. Run a periodic background scheduler (every 5 minutes) querying active database jobs created > 4 minutes ago that remain in pending status. Trigger the fallback polling query to reconcile state.
  3. Prompt Optimizer Configuration: In consumer apps, prompt_optimizer: true adds artistic flair. However, in enterprise programmatic pipelines (such as generating 50 localized variations of an automotive product), auto-expanding prompts introduces unpredictable camera angles and rogue artifacts. 365Finds strongly advises locking prompt_optimizer: false and maintaining prompt version control within your own orchestration layer.
  4. First Frame Dimension Matching: When executing Image-to-Video, ensure source images match your requested aspect ratio and resolution (e.g., exactly 1920x1080 for 16:9 1080P). Passing mismatched aspect ratios forces internal server-side letterboxing or distortion.

By combining asynchronous task dispatch, a responsive webhook handshake, dead-man polling fallback, and immediate S3 asset extraction, engineering teams can operate MiniMax Video as a headless, highly reliable video manufacturing engine.


References