Blog

Tutorial

How to Call qwen-image-3.0-pro/image-to-image via the HiAPI API: curl, Python, and a Working Request

An integration walkthrough covering the async task pattern, curl and Python clients, and error handling

Nov 10, 2026 10 min read
Cover image: misaligned, stacked paper sheets resembling offset misregistration in printing, off-white paper with charcoal-black edges and one rust-red insert, with a flat drop shadow at the lower right.
On this page

Why image-to-image is an async task

When you call an image-to-image model, you are not asking for a string completion that can stream back in a few hundred milliseconds. The model has to load your source image, run a full diffusion-style generation pass conditioned on it, and encode the output. That can take anywhere from seconds to tens of seconds, and the duration varies with resolution and settings. Holding an HTTP connection open for that entire window is a bad deal for everyone: proxies time out, load balancers drop idle sockets, and your own worker threads get pinned on a request that may still fail late.

So the endpoint uses a submit-then-poll model. Your first request submits a task and gets back immediately with a task handle. The image generation happens behind that handle. You then make separate, cheap requests to check the task's status until it reports completion, at which point the response carries the result you asked for.

This has a few practical consequences you should bake into your design from the start:

  • Submission is not completion. A successful submit call means the platform accepted your task, nothing more. Treat the two states as distinct in your code.
  • The task ID is your only handle. Persist it. If your process crashes between submit and poll, the task ID is how you resume without re-submitting (and paying for) the same work.
  • Polling is cheap but not free. Status checks are lightweight, yet a tight loop still generates traffic and can hit rate limits. Space them out.
  • Failures arrive asynchronously. A malformed image or a rejected parameter may surface as a task-level error rather than an HTTP error on submit. Your polling code has to read task state, not just status codes.

Keeping this model in mind makes the rest of the integration straightforward: one call to create work, a loop to wait for it, and deliberate handling for the three things that can go wrong.

Before you write code: what to prepare

Before touching a terminal, gather the handful of things every call in this guide depends on.

HiAPI credentials

You need an API key for HiAPI. Treat it as a secret: load it from an environment variable rather than pasting it into scripts you might commit. The examples below read it as HIAPI_API_KEY. The base URL for the API and the exact model identifier qwen-image-3.0-pro/image-to-image are the two constants you will reference throughout.

A source image

Image-to-image needs an input. Have one ready and decide how you will supply it:

  • as a publicly reachable URL, or
  • as an uploaded asset or encoded payload, depending on what the endpoint accepts.

Check the model's request schema for the exact field name and the accepted source-image formats before you write the call. Supplying a source image the endpoint does not accept is the single most common cause of a rejected task, and it is easier to rule out up front than to debug from an error message.

A client that can poll

Because the call is asynchronous, whatever you use to send the request also needs to be able to make repeated follow-up requests. curl works for the first smoke test; anything longer-lived should be a script. There is no callback URL to configure and no webhook to host — polling is the mechanism, so plan for a loop.

A place to see the result

Decide in advance what "done" looks like for you: a URL you can open in a browser, or bytes you write to disk. Knowing that before you start makes it obvious when the integration actually works.

With those four items in hand, the first request is short.

A working request with curl

The fastest way to confirm your key, the endpoint, and the task lifecycle all work is a two-step curl session. First, submit; then poll.

Step 1: submit the task

curl -sS -X POST "$HIAPI_BASE_URL/qwen-image-3.0-pro/image-to-image" \
  -H "Authorization: Bearer $HIAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "image": "https://example.com/source.jpg",
    "prompt": "restyle as a soft watercolor illustration"
  }'

Walking through it:

  • -X POST — submission is a create operation.
  • The Authorization header carries your key. Keep it out of shell history by exporting it rather than typing it inline.
  • Content-Type: application/json — the body is JSON.
  • -d — the JSON payload. The image field points at your source and prompt describes the transformation. Parameter names and accepted options come from the model's request schema; verify them there rather than guessing.

The response to a successful submit is a task object. It will include an identifier — call it the task ID — and a status field that should indicate the task is queued or running. Note the task ID; everything that follows depends on it.

Step 2: poll the task

export TASK_ID="<the id from the submit response>"

curl -sS "$HIAPI_BASE_URL/tasks/$TASK_ID" \
  -H "Authorization: Bearer $HIAPI_API_KEY"

On each call, read the status field. While it reports a pending or running state, wait a few seconds and check again. When it reports success, the response contains the generated image — usually as a URL to fetch, or as encoded data. When it reports a failure, the response carries an error description explaining why.

That is the whole lifecycle: one submit, then status checks until terminal. Anything you build afterwards is a more convenient version of these two commands, with waiting and error handling added.

The same call in Python

Repeating the two curl steps by hand gets old quickly, and copy-pasting a polling loop into every script is how subtle bugs spread. Wrap the submit-and-poll pattern in a single reusable function.

import os
import time
import requests

BASE_URL = os.environ["HIAPI_BASE_URL"]
API_KEY = os.environ["HIAPI_API_KEY"]
MODEL_PATH = "/qwen-image-3.0-pro/image-to-image"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}


def submit_task(source_image: str, prompt: str) -> str:
    resp = requests.post(
        BASE_URL + MODEL_PATH,
        headers={**HEADERS, "Content-Type": "application/json"},
        json={"image": source_image, "prompt": prompt},
        timeout=30,
    )
    resp.raise_for_status()
    return resp.json()["id"]


def wait_for_task(task_id: str, poll_interval: float = 3.0,
                  max_wait: float = 300.0) -> dict:
    deadline = time.monotonic() + max_wait
    while time.monotonic() < deadline:
        resp = requests.get(
            f"{BASE_URL}/tasks/{task_id}",
            headers=HEADERS,
            timeout=30,
        )
        resp.raise_for_status()
        task = resp.json()
        status = task["status"]
        if status == "succeeded":
            return task
        if status == "failed":
            raise RuntimeError(f"task {task_id} failed: {task.get('error')}")
        time.sleep(poll_interval)
    raise TimeoutError(f"task {task_id} did not finish within {max_wait}s")


def generate(source_image: str, prompt: str) -> dict:
    task_id = submit_task(source_image, prompt)
    return wait_for_task(task_id)

A few deliberate choices worth pointing out:

  • Separate submit from wait. If submission fails, you know it before any polling happens. If you later want to submit in one process and collect in another, the seam is already there.
  • Every request has a timeout. Requests without timeouts can hang indefinitely, which is exactly the failure mode async APIs are supposed to spare you from.
  • The poll loop has both an interval and an overall deadline. Without the deadline, a task stuck in a running state loops forever. Without the interval, you hammer the endpoint.
  • Status strings are matched explicitly. Any status that is neither success nor failure falls through to the next iteration, which is the correct default for intermediate states.

Call it the same way you would any function: generate(source_url, "make the background a dusk cityscape"). The returned object is the terminal task payload, from which you pull the image reference.

Handling errors and failed tasks

Errors in an async workflow fall into three groups, and each deserves a different response.

Request-level rejections

These are ordinary HTTP error responses to the submit call — bad or missing credentials, malformed JSON, an unsupported parameter, an unreachable source image. They arrive before any task exists.

The right response is almost always to stop and surface the message. Retrying a malformed payload just wastes quota and time. Log the status code and response body verbatim; validation messages usually name the offending field. Two cases are worth special handling: authentication failures should fail fast and loudly because they mean a configuration problem, and rate-limit responses can be retried after a backoff.

Task-level failures

Here the submit succeeded and a task ID exists, but the work failed. The polling response reports a failure status with an accompanying error.

This is the category that covers the model's own problems: the source image decoded but was unusable, the prompt was rejected, the generation hit an internal limit. Because these are specific to the input, blind retries usually reproduce the same failure. Decide per case: a transient internal error might be worth one retry; a rejected source image never will be. Log the task ID alongside the error so you can correlate it with support requests.

Polling that never finishes

The submit succeeded, the task exists, and polling runs — but no terminal state ever arrives. This is not an error returned by the platform; it is an assumption in your code that has to expire.

Guard it with a deadline, as in the Python example. When the deadline trips, stop polling. Do not silently return a half-finished result; raise or return a distinct timeout outcome so the caller can decide. Keep the task ID — the task may still complete after your deadline, and you may want to collect it later without re-submitting.

A practical rule of thumb across all three: treat the task state as the source of truth. HTTP status codes tell you whether your request was acceptable; the task's status and error fields tell you whether the work succeeded. Reading both makes failures diagnosable instead of mysterious.

Wrapping it into production code

The function above is a working integration, not a finished service. Before it carries real traffic, tighten four things.

Timeouts everywhere

Set explicit connect and read timeouts on every call — submit, poll, and any follow-up fetch of the resulting image. Then set an overall deadline for the whole task lifecycle. A timeout at the HTTP layer protects a single request; the task deadline protects the operation.

Retries with judgment

Retry only what is safe to retry. Rate-limited and transient network errors on polling qualify. Rejected payloads do not. For task-level failures, retrying means submitting a new task, which is a different and more expensive operation than retrying a status check — make that a deliberate decision, ideally capped.

Logging that includes the task ID

Log the task ID at submission and in every subsequent status transition, together with timing information. The interval between submit and first terminal state is the metric you will actually want when something feels slow. When a user reports a bad result, the task ID is the key that turns an anecdote into a traceable record.

Keeping polling off the request path

If your function runs inside a web handler, a synchronous poll loop holds a request open for the full generation time — exactly the problem the async design avoids. Instead, submit in the handler, return the task ID to the caller, and do the waiting in a background worker, queue, or scheduled job. The client then polls your service, not the model.

Build in that order and the integration goes from "works on my machine" to something you can rely on: submit, persist the handle, wait with limits, and let the task state — not hope — tell you when to stop.

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