MiniMax H3 python api: Setup Guide & Async Workflow - API

MiniMax H3 python api: Setup Guide & Async Workflow

Learn the MiniMax H3 Python API workflow, including authentication, asynchronous video tasks, status polling, file retrieval, errors, and production tips.

2026-08-03
MiniMax H3 Wiki Team
Quick Guide
  • MiniMax H3 python api uses an asynchronous create, poll, and retrieve workflow.
  • Authentication requires an API key sent through the Bearer authorization header.
  • Python integration can use requests for task creation, status checks, and file retrieval.
  • Best practice is to keep API keys in environment variables instead of source code.
  • Output handling should copy completed videos to permanent application storage.

MiniMax H3 python api at a Glance

MiniMax H3 is a multimodal AI video-generation model that accepts natural-language prompts and supported reference materials. The Python API is designed for applications that need to submit video jobs, monitor rendering progress, and retrieve completed files without keeping a request open for the entire generation process.

The standard workflow is asynchronous. Your application sends a video-generation request, receives a task_id, checks the task status at intervals, and retrieves the output after the task reaches Success. This structure works well for web applications, internal tools, content pipelines, and batch-generation systems.

Workflow StageAPI ActionApplication Result
AuthenticationSend an API key in the Authorization headerThe request is authorized
Task creationSubmit a prompt and output settingsThe API returns a task_id
Status pollingQuery the task by IDThe application tracks progress
CompletionRead the successful task responseA file_id becomes available
File retrievalRequest the file metadata or URLThe video can be downloaded

The official MiniMax H3 workflow supports short-form video generation with configurable duration and resolution. Depending on the selected endpoint and account configuration, available controls may include text prompts, image references, video references, audio instructions, aspect ratio, and output resolution.

Common ParameterExamplePurpose
modelMiniMax-H3Selects the H3 video model
promptCinematic scene descriptionDefines the visual and audio result
duration6Requests a short video duration
resolution768PSelects the output resolution
task_idReturned by creationIdentifies the asynchronous job
file_idReturned on successIdentifies the completed video file
Workflow Tip

Treat every generation as a job rather than a direct file response. Store the task ID immediately so polling can continue after temporary network interruptions.

Python API Setup and Authentication

Before writing the integration, prepare a Python environment, install the HTTP client, and store the MiniMax API key outside your application code. This approach reduces accidental key exposure in repositories, logs, screenshots, and client-side bundles.

The examples below use Python and the requests package. Install it in the environment used by your application:

python -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
pip install requests

Set the API key as an environment variable before running the script:

export MINIMAX_API_KEY="YOUR_API_KEY"

On Windows PowerShell, use:

$env:MINIMAX_API_KEY="YOUR_API_KEY"
Setup ItemRecommended PracticeWhy It Matters
API keyStore in MINIMAX_API_KEYKeeps credentials out of source files
HTTP clientUse requests with timeoutsPrevents indefinitely hanging calls
Base URLKeep it in one configuration valueMakes endpoint updates easier
PayloadValidate before submissionReduces avoidable 400 responses
LoggingNever print authorization headersProtects credentials during debugging

Hosted API

  • Managed model serving
  • Asynchronous task handling
  • File retrieval through API endpoints

Python Requests

  • Straightforward HTTP integration
  • Works for scripts and backend services
  • Easy status and error handling

Production Worker

  • Queue-based task processing
  • Retry and backoff support
  • Persistent result storage
Security Warning

Do not place the MiniMax API key in browser JavaScript, mobile client code, public notebooks, or committed configuration files. Route requests through a protected backend.

Create, Poll, and Retrieve a Video

Follow this four-stage process for a basic MiniMax H3 Python API integration. The key design principle is to separate task submission from task monitoring. A production service should be able to restart polling without submitting the same generation again.

1

Create the Video Task

Build a JSON payload with the H3 model name, prompt, duration, and resolution. Send it to the video-generation endpoint with the Bearer token. Save the returned task_id before performing any other work.

2

Poll the Task Status

Query the task endpoint using the saved ID. Continue while the task is queued, preparing, or processing. Use a delay between requests instead of sending requests continuously.

3

Handle Success or Failure

Stop polling when the status becomes Success or Fail. On success, read the file_id. On failure, record the returned error message and create a new task only after correcting the issue.

4

Retrieve the Output File

Use the completed file ID with the file-retrieval endpoint. Copy the returned download URL or file content into permanent application storage when the result must remain available.

A compact Python implementation looks like this:

import os
import time
import requests

API_KEY = os.environ["MINIMAX_API_KEY"]
BASE_URL = "https://api.minimax.io/v1"

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

payload = {
    "model": "MiniMax-H3",
    "prompt": (
        "A premium perfume bottle rotating on black glass, "
        "dramatic studio lighting, synchronized ambient sound."
    ),
    "duration": 6,
    "resolution": "768P",
}

create_response = requests.post(
    f"{BASE_URL}/video_generation",
    headers=HEADERS,
    json=payload,
    timeout=60,
)
create_response.raise_for_status()

task_id = create_response.json()["task_id"]
print("Created task:", task_id)

while True:
    query_response = requests.get(
        f"{BASE_URL}/query/video_generation",
        headers=HEADERS,
        params={"task_id": task_id},
        timeout=30,
    )
    query_response.raise_for_status()

    task = query_response.json()
    status = task.get("status")
    print("Current status:", status)

    if status == "Success":
        file_id = task["file_id"]
        print("Completed file:", file_id)
        break

    if status == "Fail":
        message = task.get("error_message", "Video generation failed")
        raise RuntimeError(message)

    time.sleep(10)
StatusMeaningRecommended Action
PreparingThe task is being initializedContinue polling
QueueingThe task is waiting for processingContinue polling with a delay
ProcessingVideo generation is underwayContinue polling
SuccessThe video is readyRetrieve the file_id
FailThe generation ended unsuccessfullyRead the error and correct the request

For a completed task, retrieve the file information using the returned ID:

file_id = "FILE_ID_FROM_SUCCESS_RESPONSE"

file_response = requests.get(
    f"{BASE_URL}/files/retrieve",
    headers=HEADERS,
    params={"file_id": file_id},
    timeout=30,
)
file_response.raise_for_status()

file_data = file_response.json()
download_url = file_data.get("file", {}).get("download_url")
if not download_url:
    download_url = file_data.get("download_url")

print("Download URL:", download_url)

The exact response shape may vary by endpoint version. During integration, inspect the JSON response and follow the current MiniMax video generation API documentation.

Reliable Pattern

Save task_id and file_id in your database when applicable. This makes the integration recoverable if the worker restarts during rendering or file retrieval.

Error Handling and Production Practices

A simple script can raise an exception when an HTTP request fails, but a production integration needs more structure. Separate client errors from temporary service errors, use bounded retries, and preserve the original task identifier.

ErrorLikely CauseHandling Strategy
400Invalid payload or unsupported settingValidate model, duration, resolution, and inputs
401Missing or invalid API keyCheck the environment variable and header
403Account or permission restrictionConfirm account access and service permissions
429Rate limit or quota reachedUse exponential backoff and queue requests
500–599Temporary service issueRetry a limited number of times
FailRendering task ended unsuccessfullyRead the task message and revise the request

Use exponential backoff for temporary failures instead of retrying immediately:

import time

def wait_with_backoff(attempt, base_delay=5, max_delay=60):
    delay = min(base_delay * (2 ** attempt), max_delay)
    time.sleep(delay)

For polling, apply a maximum wait time so a worker does not remain active indefinitely:

started_at = time.time()
max_wait_seconds = 30 * 60

while time.time() - started_at < max_wait_seconds:
    # Query the task here.
    # Break on Success or Fail.
    time.sleep(10)

raise TimeoutError("The MiniMax H3 task exceeded the polling limit.")

Use these practices when moving beyond a local test:

  • Keep prompts and payloads reproducible. Store the prompt, model, duration, resolution, and reference-file identifiers.
  • Use a background worker. Web requests should create jobs, not wait for the full video render.
  • Prevent duplicate submissions. Assign an internal request ID before calling the create endpoint.
  • Validate inputs early. Reject missing files, unsupported formats, and conflicting settings before API submission.
  • Protect output URLs. Treat returned download links as application data and copy important files into controlled storage.
  • Monitor usage. Track successful tasks, failed tasks, retry counts, and total generated seconds.

Production Readiness Checklist:

  • Store the API key in a protected environment variable
  • Save every returned task ID
  • Use request timeouts and bounded retries
  • Poll with a delay and maximum wait time
  • Persist completed videos in permanent storage
Important Limitation

Downloading open H3 model weights is separate from using the hosted API. Hosted service features, platform-side processing, and API file delivery should not be assumed to exist in a local deployment.

MiniMax H3 Python API FAQ

Q: Is the MiniMax H3 Python API synchronous?

No. The standard integration is asynchronous. Create a task, save its task_id, poll the query endpoint, and retrieve the file after the task reaches Success.

Q: Where should I store the MiniMax H3 API key?

Store it in a protected environment variable or secret manager. Avoid hard-coding it in Python files, public repositories, browser code, or application logs.

Q: What should I do when a task returns Fail?

Read the returned error information, check the prompt and request settings, verify reference inputs, and submit a new task only after correcting the problem.

Q: Can I use the same Python workflow for local H3 weights?

Not directly. The hosted API uses HTTP endpoints and task IDs, while local weights require the repository's inference environment, dependencies, hardware configuration, and execution commands.

The safest starting point is a small backend script that creates one short H3 task, polls it with timeouts, retrieves the result, and records every response needed for debugging. Once that path works, add queues, persistent storage, retry policies, and application-level request tracking.