Qwen Image 3.0 API setup starts with a regional Model Studio key and the qwen-image-3.0 model on Alibaba’s documented image-generation endpoint. The same synchronous request can generate from text or edit a reference image, and its response supplies a PNG download URL. This walkthrough takes that request through saving the image, reusing a local result and estimating the $0.03 international output-image charge.
Don't miss new tech stories on Google
Add Tech Insider once in the Google app and our stories appear in your news suggestions.
Match the workspace, region and key before sending a request
In Model Studio, select the region where your model is available, obtain a key for that region and copy the workspace ID from Workspace Details. The API reference requires the model, endpoint and key to belong to the same region. The example below uses Singapore throughout. Use the matching regional key when changing the endpoint.
Store the workspace ID as QWEN_WORKSPACE_ID. Supply the key through DASHSCOPE_API_KEY, or leave that variable unset and enter it at the script’s hidden prompt. Do not echo the key to verify it. The following macOS or Linux command sets only the non-secret workspace identifier; replace the value with the ID shown in your console.
export QWEN_WORKSPACE_ID='your-workspace-id'
Alibaba recommends workspace-specific domains while retaining the older generic domain. For Singapore, the compatible API route ends in /compatible-mode/v1/images/generations. Its request parameters sit at the top level of the JSON body. This differs from native DashScope’s nested input.messages and parameters, so select a protocol before adapting an example.
This is a hosted API workflow. Deploying a model on your own machine is a separate task, covered in the Qwen-Image-2.1 local setup guide. The script here sends requests to the selected cloud workspace and saves the returned files locally.
A Python request that saves the returned PNG
Save the following as qwen_image.py. It uses Python’s standard library, so this path needs no SDK installation. Its request follows Alibaba’s compatible schema: model, prompt, size and integer n. The result is read from data, and the download uses the returned url. Alibaba says the URL expires after 24 hours, so the script downloads it immediately.
import argparse
import base64
import getpass
import hashlib
import json
import mimetypes
import os
from pathlib import Path
import time
from urllib.error import HTTPError
from urllib.parse import urlparse
from urllib.request import Request, urlopen
parser = argparse.ArgumentParser()
parser.add_argument('prompt_file')
parser.add_argument('--reference')
args = parser.parse_args()
workspace = os.environ['QWEN_WORKSPACE_ID']
region = 'ap-southeast-1'
if not workspace or not all(c.isalnum() or c == '-' for c in workspace):
raise ValueError('Use the workspace ID from your console')
endpoint = (f'https://{workspace}.{region}.maas.aliyuncs.com'
'/compatible-mode/v1/images/generations')
prompt = Path(args.prompt_file).read_text(encoding='utf-8').strip()
if not prompt:
raise ValueError('The prompt file is empty')
payload = {'model': 'qwen-image-3.0', 'prompt': prompt,
'size': '1536x1024', 'n': 1, 'prompt_extend': True}
if args.reference:
reference = Path(args.reference)
mime = mimetypes.guess_type(reference.name)[0]
accepted = {'image/jpeg', 'image/png', 'image/bmp', 'image/tiff',
'image/webp', 'image/gif'}
if mime not in accepted:
raise ValueError('Use a supported reference-image format')
raw = reference.read_bytes()
if len(raw) > 10_000_000:
raise ValueError('Keep the reference below 10 MB')
payload['image'] = f'data:{mime};base64,{base64.b64encode(raw).decode()}'
body = json.dumps(payload).encode()
cache_key = hashlib.sha256(endpoint.encode() + body).hexdigest()
folder = Path('qwen-output')
folder.mkdir(exist_ok=True)
output = folder / f'{cache_key}.png'
if output.exists():
print(f'Using saved image: {output}')
raise SystemExit
key = os.environ.get('DASHSCOPE_API_KEY') or getpass.getpass('API key: ')
request = Request(endpoint, data=body, headers={
'Authorization': f'Bearer {key}', 'Content-Type': 'application/json'})
for attempt in range(4):
try:
with urlopen(request, timeout=600) as response:
result = json.load(response)
print('Request ID:', response.headers.get('x-request-id'))
break
except HTTPError as error:
request_id = error.headers.get('x-request-id')
if error.code != 429 or attempt == 3:
raise RuntimeError(f'HTTP {error.code}; request ID {request_id}') from None
delay = error.headers.get('Retry-After', '')
time.sleep(min(int(delay), 60) if delay.isdigit() else 2 ** attempt)
# Other failures stop here: do not blindly resubmit an ambiguous request.
image_url = result['data'][0]['url']
if urlparse(image_url).scheme != 'https':
raise ValueError('Expected an HTTPS result URL')
# Download separately, without forwarding the API Authorization header.
temporary = output.with_suffix('.part')
try:
with urlopen(image_url, timeout=60) as response:
image_bytes = response.read()
if not image_bytes.startswith(b'\x89PNG\r\n\x1a\n'):
raise ValueError('Response is not a PNG file')
temporary.write_bytes(image_bytes)
temporary.replace(output)
finally:
temporary.unlink(missing_ok=True)
(folder / f'{cache_key}.json').write_text(
json.dumps({'usage': result.get('usage', {}), 'file': str(output)}, indent=2),
encoding='utf-8')
print('Saved:', output)
print('Usage:', result.get('usage', {}))
The cache identifies the endpoint and full request body, including reference-image content. An identical request reuses the saved PNG; changing the prompt, size or reference creates a different cache key. Delete that saved image when you deliberately want a new generation from the same request. Downloads use a temporary file and are renamed only after a PNG signature check, keeping an interrupted download from becoming the cache’s completed image.
The generation timeout is 600 seconds, following Alibaba’s guidance for long-running or multi-image requests. The timeout sets how long this client waits for generation. Only an explicit HTTP 429 response enters the bounded retry loop; a connection failure or timeout stops the script, leaving the operator to decide whether another submission is appropriate.
Create dashboard.txt with an explicit layout, then run the command below. An application can prepare that text in a separate language-model stage; the OpenAI Responses API guide covers that provider’s client setup. Keep the final image request on the Alibaba endpoint shown here. These are example labels for a mockup, not business data.
Design a warehouse dashboard on a light background.
Top bar: "Warehouse Overview". Left menu: "Stock", "Orders", "Alerts".
Main area: a stock-level chart and a separate low-stock list.
Use these exact list labels: "Packaging", "Labels", "Pallets".
Keep chart labels outside the bars and leave space between sections.
python3 qwen_image.py dashboard.txt
Use reference images without changing the endpoint
For an edit, put the instruction in edit.txt and add a local image path. In the command below, replace dashboard.png with the saved PNG path printed by the generation run. The script encodes it as a data URL and supplies the image field. Alibaba’s compatible editing API uses the same generations endpoint; it does not use multipart uploads to /images/edits. Asking for b64_json output would not change the response into Base64: the documented response remains image URLs.
python3 qwen_image.py edit.txt --reference dashboard.png
For example, write: “Keep the menu labels and chart placement. Change the background to dark gray and the accent color to purple.” For an educational graphic, use named stages and exact labels in the prompt instead of the dashboard example. Inspect the resulting labels and sequence before sharing the diagram.
| Parameter | Qwen Image 3.0 requirement | Use in this example |
|---|---|---|
| Reference images | 1 to 3 per request | One local image; the API also accepts public URLs |
| Input dimensions | 1 to 8000 pixels on each side; recommended 384 to 2048 | Check the file dimensions before running |
| Input aspect ratio and size | Longest side at most 10 times shortest; up to 10 MB | Script checks a conservative byte limit; inspect dimensions separately |
| Output pixel area | 512Ă—512 through 2048Ă—2048, for generation and editing | 1536Ă—1024 falls within this range |
| Output aspect ratio | 1:8 through 8:1 | The example uses a landscape format |
| Output count | Integer 1 to 6 | The script requests 1 PNG |
| Prompt length | Recommended maximum 4,500 tokens | Keep the layout instruction focused |
Check reference-image requirements when changing models. QwenCloud’s model guide says the Qwen-Image-2.1 series supports up to 10 references and alpha-channel output. The reference limit for the 3.0 series remains smaller, so an existing multi-reference pipeline should validate its request shape before switching models.
Keep request tracing separate from asynchronous jobs
The compatible API is synchronous and non-streaming. Its x-request-id HTTP header identifies a request for tracing; use it when investigating that request. The script prints that header after success and includes it in terminal HTTP errors. The synchronous call returns its result directly.
Alibaba documents a separate DashScope asynchronous flow: submit to the native /api/v1/services/aigc/image-generation/generation route with X-DashScope-Async: enable, then use the returned task_id with the query API. That route differs from native synchronous multimodal-generation/generation. Moving a queued production job to asynchronous mode therefore requires changing the protocol deliberately, not adding a polling loop to this synchronous script.
| Failure or unexpected behavior | Check before resubmitting |
|---|---|
| Cross-region request failure | Align workspace endpoint, model availability and key region |
| Invalid output count | Send an integer n, not a quoted numeric string |
| Editing rejects agent prompt enhancement | Use direct mode for edits; agent mode is text-to-image only |
| Size rejected after copying native code | Use x in compatible size values; native DashScope uses * |
| Expected Base64 output but received a URL | Download the documented URL instead of waiting for b64_json |
| HTTP 429 | The example backs off and stops after its bounded attempts |
| Timeout or interrupted connection | The example stops; do not assume the server did no work |
Budget for images, including references and extra outputs
The standard model page and Pro model page list the following international rates. QwenCloud says models, prices and rate limits follow the selected region, so use the corresponding regional price view when deploying elsewhere.
| International model | Input image | 1K output image | 2K output image | Requests per minute |
|---|---|---|---|---|
| qwen-image-3.0 | $0.003 | $0.03 | $0.03 | 20 |
| qwen-image-3.0-pro | $0.003 | $0.04 | $0.075 | 5 |
At the published international rates, 10,000 standard-model outputs cost $300. Editing with one reference and one output per call costs $330 for that batch, including $30 in input-image charges.
A standard request returning 6 images costs $0.18 for the outputs, before any reference-image charges. Set the queue’s output-image budget alongside its requests-per-minute limit. Keep the script’s single-output setting until the downstream download and accounting paths handle multiple results.
The successful response usage fields report actual input and output image counts, rather than token usage. The script saves that usage beside the PNG. Use the saved usage fields to reconcile the generated results with the workload budget.
Inspect a dashboard draft before expanding the workload
Begin with a single layout, open the saved PNG and compare its menu labels, chart labels and spacing against the prompt. Then change one instruction and generate again. Repeat the unchanged command once to confirm that the local saved-image path is reused. This separates a request-construction problem from a rendering issue and checks that the example’s cost-saving behavior matches your intended workflow.
Alibaba’s prompt controls include rewriting, a fixed seed and a negative prompt. Thinking is enabled by default, requires prompt rewriting and can increase generation time. Record the model and these settings with a prompt you intend to reuse, rather than assuming that changing them leaves the layout behavior unchanged. Keep the seed with the prompt when comparing revisions.
In our view, the useful first milestone is a saved, readable diagram with a traceable request and recorded image usage. After that works for the intended layout, adapt the queue size and output count to the regional limits. Keep the region, schema, response handling and image-count budget together when promoting the script into an application: each is part of the same integration.




