Blog

Tutorial

How to Use minimax-h3-image text-to-image via the HiAPI API: curl and Python

Nov 13, 2026 10 min read
Flat woven-style cover image: a square weave pattern of interlocking deep brown and oatmeal wide fabric bands, accented with a few brass-colored woven edges.
On this page

What this tutorial covers and what you need first

This tutorial walks through one concrete task: sending an image-generation prompt to the minimax-h3-image text-to-image model through the HiAPI API, first with a single curl request, then with a small Python function you can drop into an application. It covers the shape of the request, how to read the response, how errors surface, and what to tighten up before the call ships to production.

It deliberately does not cover prompt engineering theory, image post-processing, or building a UI. The goal is narrower: by the end you should have a request you trust and know exactly why it failed the last time it did.

Prerequisites

  • A HiAPI account. You need a project and an API key before anything else — every request below is authenticated.
  • Your key stored somewhere safe. Keep it in an environment variable (HIAPI_API_KEY) rather than in source files, so the same code works locally and in CI.
  • The model identifier. This tutorial uses minimax-h3-image with the text-to-image capability. Treat both the model name and the task path as configuration values in your code, not magic strings scattered everywhere.
  • Tooling. curl for the first request, Python 3.9+ with requests for the second. No other libraries are required.
  • A way to inspect images. You will be reading a response payload that contains either image data or a reference to it — check the response fields once, by hand, before you assume a schema.

One habit to adopt now

Generate your first successful request outside your application code. A working curl command is the ground truth you will compare against whenever the Python version misbehaves. If the curl call works and Python does not, the problem is in your client, not in the model or the network.

Build a working text-to-image request with curl

Start with the smallest request that can possibly succeed, then add settings back one at a time. A generation request has three parts: the endpoint, the auth header, and the JSON body.

The request

curl -X POST "https://api.hiapi.ai/v1/images/generations" \
  -H "Authorization: Bearer $HIAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "minimax-h3-image",
    "task": "text-to-image",
    "prompt": "A single ceramic bowl on a linen tablecloth, soft north window light, 50mm lens, shallow depth of field",
    "size": "1024x1024",
    "n": 1
  }'

Three things matter in that command:

  • The key is passed as a bearer token in the Authorization header. Never put it in the URL or the body, where it will end up in logs and shell history.
  • model and task describe what you want — the model family and the capability. Keep both explicit even if a default exists; explicit requests age better.
  • The prompt is a plain string. Everything else (size, n) is an image setting, not a description of the subject.

Reading the response

Pipe the output through a formatter so you can actually read it:

curl -s -X POST "https://api.hiapi.ai/v1/images/generations" \
  -H "Authorization: Bearer $HIAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d @request.json | python -m json.tool

When iterating, put the body in a file (request.json) — it keeps the prompt readable and makes prompt edits a one-line diff instead of a quoting puzzle.

Inspect the payload before writing a parser. Note whether images come back inline or as URLs, which fields carry the image identifier and any revised prompt, and whether the response includes usage metadata. Write those field names down; your Python client will depend on them.

Confirm the loop end to end

Save the returned image, open it, and check that what you asked for is what arrived. A 200 response with a plausible-looking JSON body is not the same as a correct image — this is the point where prompt and parameter problems are cheapest to catch.

Translate the request into Python

Now port the exact same request. Keep it boring: one function, explicit timeout, no hidden retries yet.

import os
import requests

HIAPI_API_KEY = os.environ["HIAPI_API_KEY"]
ENDPOINT = "https://api.hiapi.ai/v1/images/generations"


def generate_image(prompt: str, size: str = "1024x1024", n: int = 1) -> dict:
    """Generate images with minimax-h3-image via HiAPI."""
    payload = {
        "model": "minimax-h3-image",
        "task": "text-to-image",
        "prompt": prompt,
        "size": size,
        "n": n,
    }
    response = requests.post(
        ENDPOINT,
        headers={
            "Authorization": f"Bearer {HIAPI_API_KEY}",
            "Content-Type": "application/json",
        },
        json=payload,
        timeout=(5, 120),  # connect timeout, read timeout
    )
    response.raise_for_status()
    return response.json()

Four deliberate choices in that function:

  • A tuple timeout. The connect timeout is short because a slow connection setup means something is wrong; the read timeout is generous because image generation genuinely takes time. A single timeout value forces you to choose one failure mode to be bad at.
  • json=payload. Let the library serialize the body. Hand-built JSON strings are where quoting bugs live.
  • raise_for_status() before parsing. Status checking is not optional — an error body parsed as if it were a success is the most confusing bug class in this integration.
  • A plain dict return. You can decorate it with typed models later; first make sure you know which fields the response actually contains.

Isolate the key lookup

os.environ["HIAPI_API_KEY"] raises immediately if the variable is missing. That is intentional: fail at startup, not on the first user request. In a larger codebase, resolve the key once during configuration loading and pass a configured client around rather than reading the environment at call sites.

Wire it in

if __name__ == "__main__":
    result = generate_image("A red kite above a wet beach at low tide, overcast light")
    print(result)

Run it and compare against the curl output. The payload shapes should match. If they do not, you have found a discrepancy worth understanding before building on top of it.

Handle errors without guessing

The most common integration bug is retrying an error that will never succeed. Sort failures into three categories and treat each differently.

Authentication and authorization failures

These typically appear as 401 or 403. Causes: missing header, malformed Bearer prefix, a revoked or misconfigured key, or a project without access to the model. They are not retryable. Retrying just burns time and pollutes your logs with identical failures. Fix the credential and move on.

Request validation failures

These are usually 400-class responses: an unknown model or task value, a size the model does not support, n out of range, an empty prompt, malformed JSON. They are also not retryable — the same request will fail identically. The useful work is surfacing the error message verbatim to the developer who wrote the request, not swallowing it in a generic exception.

Transient server and network failures

429 and 5xx responses, plus connection resets and read timeouts, are the genuinely retryable class. Handle them with bounded exponential backoff and jitter:

import time, random, requests

def post_with_retry(session, url, payload, max_attempts=4):
    for attempt in range(max_attempts):
        try:
            r = session.post(url, json=payload, timeout=(5, 120))
            if r.status_code in (429, 500, 502, 503, 504):
                raise requests.HTTPError(f"transient {r.status_code}", response=r)
            r.raise_for_status()
            return r.json()
        except (requests.ConnectionError, requests.Timeout, requests.HTTPError) as exc:
            if attempt == max_attempts - 1:
                raise
            time.sleep(min(2 ** attempt + random.random(), 30))

Two cautions. First, a raised HTTPError from a 4xx that is not 429 must escape immediately — do not let the except clause absorb validation failures. Second, respect any retry guidance the response carries rather than inventing your own delay.

Retries are not idempotent here

Every retried generation is a new billable generation. If a request timed out, the image may still have been produced and charged. Keep retry counts small, log the attempt number alongside request metadata, and prefer surfacing a clear failure over silently generating the same image four times.

Practical prompt and parameter hygiene

The point of these habits is comparability: when you change one thing, you should be able to tell whether the output changed because of it.

Write prompts that name what is in frame

Describe subject, setting, lighting, and framing in that order. Concrete nouns and photographic terms ("soft north window light", "shallow depth of field") carry more signal than stacks of aesthetic adjectives. Avoid negation-heavy prompts; describe what should be present.

Change one variable at a time

Keep a small prompt file per project and edit between runs rather than rewriting from scratch. If a run disappoints, change either the prompt or the settings — not both. Otherwise you learn nothing about which change mattered.

Treat settings as an explicit contract

size and n affect both output and cost. Fix them in one config object rather than threading literals through call sites, so that changing the aspect ratio for a whole feature is a single edit. If you need multiple images for comparison, request them in one call rather than several — fewer round trips, easier logs.

Store the prompt with the output

Persist the exact prompt string, the settings, and the model identifier next to every generated image. A prompt you cannot reproduce is an image you cannot regenerate, debug, or improve. This one habit saves more time than any prompt trick.

Seed your comparisons

The same prompt can produce different images across runs. When you are evaluating a change, compare aggregates — several images per configuration — rather than trusting a single lucky or unlucky sample.

Version your prompts

Treat prompt text as code: keep it in a file, review changes, and record which prompt version produced which asset. It makes "why did the images get worse last Tuesday?" an answerable question.

Production checklist before you ship

The working request is the easy part. These are the checks that separate a demo from an integration.

  • Timeouts on every call. Connect and read timeouts set explicitly, never defaults. A generation endpoint without a read timeout will eventually hang a worker.
  • Bounded retries, retryable errors only. Cap attempts, add jitter, and make sure validation and auth failures bypass the retry path entirely.
  • Key management. Read the key from the environment or a secret store, never from source. Rotate it without a code change.
  • Structured logging. Log the model identifier, the prompt (or a hash plus a reference), the settings, the HTTP status, the attempt number, and any request identifier in the response. Without this, image problems are unreproducible.
  • Cost visibility. Generation is billed by output, so usage is a function of how many images you ask for and how often you retry. Decide up front whether requests are per-user, per-job, or background, and track volume accordingly — check the live pricing panel on the site for current rates rather than hard-coding assumptions.
  • Failure behavior defined. Decide what happens to the user when generation fails after the final attempt: error state, placeholder, or queued retry. An undefined fallback becomes an undefined user experience.
  • Payload schema pinned. Store and validate the response fields you depend on, so a payload change surfaces as an explicit error rather than a silent None.

Final verification pass

Run the curl command, the Python function, and a deliberately broken request (bad key, then bad parameter) and confirm each produces the failure you expect. That last step is what tells you the error handling is real and not decorative.

With the request authenticated, ported, retried sensibly, and logged, the integration is ready to sit behind the rest of your application.

Related articles

View all articles →

Start building with persistent AI artifacts

Get your API key and call image, video and audio models through one task-based API.

Read the API docs