Tutorial
How to Use qwen-image-2.0-pro via the HiAPI API: curl, Python, and a Working Request
A hands-on integration walkthrough for developers: first successful call, request anatomy, and troubleshooting
On this page
What qwen-image-2.0-pro Gives You as an API Consumer
qwen-image-2.0-pro is an image generation model you call over HTTP. From your code's point of view, it behaves like a chat-completions endpoint: you send a JSON payload describing the image you want, and you get back a JSON response containing the generated image.
The advantage of reaching it through the HiAPI API is consistency. One API key, one base URL, and one request shape work across models. If you later swap the model identifier or adjust a parameter, the surrounding code stays the same. You do not need to learn a new SDK or manage multiple credentials for each image model you experiment with.
This tutorial walks through a complete first call in curl, then ports it to Python, explains how to read the image out of the response, and ends with a troubleshooting checklist and a small reusable wrapper. Every example uses the same payload and the same environment variable for the key, so what works in your terminal will work unchanged in a script.
Prerequisites and Getting Your Key Ready
Before writing any code, make sure you have three things in place.
1. A HiAPI account and API key
Create an account and generate an API key from the dashboard. The key is a secret; treat it like a password. Do not paste it into source files that get committed to version control.
2. The key exported as an environment variable
The examples below read the key from HIAPI_API_KEY, so the same command and script work locally and in CI without edits.
export HIAPI_API_KEY="your_key_here"
On Windows PowerShell, use $env:HIAPI_API_KEY = "your_key_here". In CI, set it as a secret environment variable in your pipeline configuration.
3. A tool for making HTTP requests
curl is usually already installed. For Python, you need Python 3 and the requests library:
pip install requests
You can confirm the key is visible to your shell before proceeding:
# macOS / Linux
echo "${HIAPI_API_KEY:0:4}..."
If that prints nothing, the variable is not set and every request will fail with an auth error. Fix that first.
A Minimal Working Request with curl
The fastest way to confirm connectivity is a single curl call that reads the key from the environment variable. The payload is a JSON object with a model field and a messages array in the chat-completions style.
curl -sS https://api.hiapi.ai/v1/chat/completions \
-H "Authorization: Bearer $HIAPI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-image-2.0-pro",
"messages": [
{
"role": "user",
"content": "A small ceramic mug on a wooden table, soft morning light, product photo"
}
]
}'
Three details matter here. The Authorization header uses the Bearer scheme. The model value matches the model identifier exactly. The content is a plain string prompt describing the image.
If the request succeeds, you will see a JSON response printed to your terminal. If it fails, you will see an HTTP status code and an error message. Check the status code before reading the body: 401 means the key is wrong or missing, 400 usually means the payload is malformed, and a 404 or model-not-found error means the model identifier is off.
Once this command returns a successful response, connectivity is confirmed and you can move to code.
The Same Request in Python
Porting the call to Python keeps the payload identical. The only differences are how you read the environment variable and how you serialize the request.
import json
import os
import requests
api_key = os.environ["HIAPI_API_KEY"]
payload = {
"model": "qwen-image-2.0-pro",
"messages": [
{
"role": "user",
"content": "A small ceramic mug on a wooden table, soft morning light, product photo",
}
],
}
response = requests.post(
"https://api.hiapi.ai/v1/chat/completions",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
json=payload,
timeout=120,
)
response.raise_for_status()
data = response.json()
print(json.dumps(data, indent=2))
Notice that json=payload lets requests set the Content-Type header and serialize the body for you. The timeout is important because image generation can take longer than a typical text completion; 120 seconds is a reasonable starting point. raise_for_status() turns a bad status code into an exception, so failures are not silent.
Run this script and you should get the same JSON you saw from curl. If you do not, something in your environment differs from the shell where curl worked, most often the key variable.
Reading the Response and Handling the Image Output
The response follows the chat-completions shape, so the generated image is reached through the same path you would use for a text reply. Inspect the printed JSON first; the structure will be familiar:
{
"choices": [
{
"message": {
"role": "assistant",
"content": "..."
}
}
]
}
The generated image appears in the assistant message content, typically as a URL or a base64-encoded payload depending on how the model returns media. Do not assume which one; read the value and branch on its prefix:
content = data["choices"][0]["message"]["content"]
if isinstance(content, str) and content.startswith("http"):
image_url = content
# Download and save if you want a local copy
image_bytes = requests.get(image_url, timeout=60).content
with open("output.png", "wb") as f:
f.write(image_bytes)
print("saved output.png from URL")
else:
# Treat as base64-encoded image data
import base64
image_bytes = base64.b64decode(content)
with open("output.png", "wb") as f:
f.write(image_bytes)
print("saved output.png from base64")
Two practical notes. If the content is a URL, treat it as temporary and download it promptly rather than linking it directly in a product. If it is base64, keep the decode isolated so a malformed payload raises an error you can catch. Always write the raw response to a log file before parsing, so you can debug without re-running a potentially slow request.
A Troubleshooting Checklist for Failed Requests
When a request fails, resist the temptation to rewrite the whole call. Work through these checks in order, and stop at the first one that fails. Each check isolates one variable.
1. Authentication
Check the status code first. A 401 means the key is missing, expired, or malformed. Confirm the environment variable is set in the current shell, that you are using the Bearer prefix, and that there are no trailing spaces in the header.
2. Model identifier
A model-not-found error means the model value does not match an available model exactly. Casing and suffixes matter. Compare your value character by character against the model's documentation page.
3. Payload shape
A 400 often comes from a malformed body. Confirm that messages is an array, that each message has both role and content, and that your JSON is valid. Sending the payload through jq or python -m json.tool catches syntax errors before you send anything.
4. Response handling
If the request succeeds but your script crashes, the bug is in your parsing, not the API. Log the raw response body before slicing into it, and confirm the path you are reading actually exists. The image may come back as a URL on one call and base64 on another, so branch on the content rather than assuming.
5. Timeouts and retries
Image generation can be slow. If you see a timeout, increase the client timeout and retry once. Avoid retrying on 4xx errors, since they will fail again identically.
A useful habit: keep a single saved copy of a known-good request and diff your failing request against it. Most failures are one field away from working.
Wrapping It Into a Reusable Client
Once the call works, put it behind a small function so model and parameter changes stay in one place. This wrapper keeps the key lookup, headers, and error handling centralized:
import base64
import os
import requests
HIAPI_BASE = "https://api.hiapi.ai/v1"
DEFAULT_MODEL = "qwen-image-2.0-pro"
def generate_image(prompt: str, model: str = DEFAULT_MODEL) -> bytes:
"""Generate an image and return its raw bytes."""
api_key = os.environ["HIAPI_API_KEY"]
payload = {
"model": model,
"messages": [{"role": "user", "content": prompt}],
}
response = requests.post(
f"{HIAPI_BASE}/chat/completions",
headers={"Authorization": f"Bearer {api_key}"},
json=payload,
timeout=120,
)
response.raise_for_status()
content = response.json()["choices"][0]["message"]["content"]
if isinstance(content, str) and content.startswith("http"):
return requests.get(content, timeout=60).content
return base64.b64decode(content)
Calling code becomes one line: open("out.png", "wb").write(generate_image("A ceramic mug on a wooden table")). If you later switch to another image model or add parameters, only this function changes. Model identifiers and any parameter details live on the model page, and you can review the qwen-image-2.0-pro model details before wiring it in.
Start with the curl call, then the Python script, then wrap it. Each step confirms a smaller piece before you build on it.
Related articles
View all articles →-
Tutorial
kling-image-4.0 Real-World Use Cases: 5 High-Value Applications and Integration Essentials
-
Tutorial
How to Call gemini-omni-1.1-flash via the HiAPI API: curl and Python Guide
10 min read -
Tutorial
How to Call the veo-3.1 Text-to-Video API: curl and Python Examples
A hands-on integration walkthrough for developers
8 min read