The Wan text-to-image model generates images from text prompts, supporting artistic styles and realistic photographic effects.
Quick links: Try online (Beijing | Singapore | Virginia) | Wan official website | Text-to-image user guide
Wan website features may differ from API capabilities. This document covers the API and is updated as changes occur.
Model overview
|
Model name |
Model description |
Output image format |
|
wan2.6-t2i |
Wan 2.6 Supports flexible dimensions within total pixel area and aspect ratio constraints (same as wan2.5). |
Image resolution: Total pixels between 1280×1280 and 1440×1440. Image aspect ratio: [1:4, 4:1] |
|
wan2.5-t2i-preview |
Wan 2.5 preview Supports flexible dimensions within total pixel area and aspect ratio constraints. For example, it supports 768×2700, while version 2.2 and earlier have a single-side limit of 1400. |
|
|
wan2.2-t2i-flash |
Wan 2.2 Flash 50% faster than the 2.1 model. |
Image resolution: Both width and height are between 512 and 1440 pixels. Image format: png |
|
wan2.2-t2i-plus |
Wan 2.2 Pro Improved stability and success rate compared to the 2.1 model. |
|
|
wanx2.1-t2i-turbo |
Wan 2.1 Flash |
|
|
wanx2.1-t2i-plus |
Wan 2.1 Pro |
|
|
wanx2.0-t2i-turbo |
Wan 2.0 Flash |
-
Before you call the API, see the Recommended models for models supported in each region.
-
wan2.6 model: Supports HTTP synchronous calls, HTTP asynchronous calls, DashScope Python SDK calls, and DashScope Java SDK calls.
-
wan2.5 and earlier models: Support HTTP asynchronous calls, DashScope Python SDK calls, and DashScope Java SDK calls. They do not support HTTP synchronous calls.
Prerequisites
Before making a call, get an API key and export the API key as an environment variable. To make calls using the SDK, install the DashScope SDK.
The China (Beijing), Singapore, and US (Virginia) regions have separate API keys and request endpoints. They cannot be used interchangeably. Cross-region calls lead to authentication failures or service errors. For more information, see Select a region and service deployment scope.
HTTP synchronous (wan2.6)
The API in this section uses the new protocol and supports only the wan2.6 model.
Retrieve the result in a single request. Recommended for most use cases.
China (Beijing)
POST https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
Singapore
POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
When calling, replace WorkspaceId with your actual workspace ID.
US (Virginia)
POST https://dashscope-us.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
Request parameters |
Text-to-image
|
Request headers |
|
|
Content-Type The content type of the request. Must be |
|
|
Authorization Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx. |
|
Request body |
|
|
model The model name. Example: wan2.6-t2i. Note
For wan2.5 and earlier models, see HTTP asynchronous call for HTTP calls. |
|
|
input The input object. |
|
|
parameters Image generation parameters. |
Response parameters |
Successful task executionTask data (task status and image URLs) is retained for only 24 hours and then automatically purged. Save generated images promptly.
Task execution failedIf the task fails, the API returns error information. Identify the cause from the code and message fields. See Error codes.
|
|
output The output object. |
|
|
usage Usage statistics for the request. Only successful results are counted. |
|
|
request_id Unique request identifier for tracing and troubleshooting. |
|
|
code Error code. Returned only for failed requests. See Error codes. |
|
|
message Detailed error message. Returned only for failed requests. See Error codes. |
HTTP asynchronous (wan2.6)
The API in this section uses the new protocol and supports only the wan2.6 model.
The task flow includes two core steps: Create task -> Poll for result. The process is as follows:
Step 1: Create a task and get the task ID
China (Beijing)
POST https://dashscope.aliyuncs.com/api/v1/services/aigc/image-generation/generation
Singapore
POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation
When calling, replace WorkspaceId with your actual workspace ID.
US (Virginia)
POST https://dashscope-us.aliyuncs.com/api/v1/services/aigc/image-generation/generation
Germany (Frankfurt)
POST https://<u>{WorkspaceId}.eu-central-1.maas.aliyuncs.com</u>/api/v1/services/aigc/image-generation/generation
When you make a call, replace WorkspaceId with your Workspace ID.
-
After the task is created, use the returned
task_idto query the result. Thetask_idis valid for 24 hours. Do not create duplicate tasks. Instead, use polling to retrieve the result. -
For guidance for beginners, see Call APIs with Postman or cURL.
Request parameters |
Text-to-image
|
Request headers |
|
|
Content-Type The content type of the request. Must be |
|
|
Authorization Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx. |
|
|
X-DashScope-Async Enables asynchronous processing. HTTP requests support only asynchronous calls. Must be Important
If this request header is missing, the error "current user api does not support synchronous calls" is returned. |
|
Request body |
|
|
model The model name. Example: wan2.6-t2i. Note
For wan2.5 and earlier models, see HTTP asynchronous call. |
|
|
input The input object. |
|
|
parameters Image generation parameters. |
Response parameters |
Successful responseSave the
Error responseTask creation failed. See Error codes.
|
|
output The output object. |
|
|
request_id Unique request identifier for tracing and troubleshooting. |
|
|
code Error code. Returned only for failed requests. See Error codes. |
|
|
message Detailed error message. Returned only for failed requests. See Error codes. |
Step 2: Query the result by task ID
China (Beijing)
https://dashscope.aliyuncs.com/api/v1
Singapore
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
When calling, replace WorkspaceId with your actual workspace ID.
US (Virginia)
https://dashscope-us.aliyuncs.com/api/v1
Germany (Frankfurt)
https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1
Replace WorkspaceId with your actual Workspace ID.
-
Polling recommendation: Image generation is time-consuming. Use a polling mechanism with a reasonable interval, such as 10 seconds.
-
Task state transition: PENDING → RUNNING → SUCCEEDED or FAILED.
-
Result link: After a task succeeds, an image URL valid for 24 hours is returned. Download and save the image to permanent storage, such as OSS.
-
Requests Per Second (RPS) limit: The default RPS for the query API is 20. For higher-frequency queries or event notifications, we recommend that you configure an asynchronous task callback.
-
More operations: For batch queries, task cancellation, and other operations, see Manage asynchronous tasks.
Request parameters |
Query task resultReplace |
Request headers |
|
|
Authorization Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx. |
|
URL path parameters |
|
|
task_id The ID of the task. |
Response parameters |
Successful task executionTask data (task status and image URLs) is retained for only 24 hours and then automatically purged. Save generated images promptly.
Task execution failedIf the task fails, the API returns error information. Identify the cause from the code and message fields. See Error codes.
|
|
output The task output information. |
|
|
usage Usage statistics for the request. Only successful results are counted. |
|
|
request_id Unique request identifier for tracing and troubleshooting. |
|
|
code Error code. Returned only for failed requests. See Error codes. |
|
|
message Detailed error message. Returned only for failed requests. See Error codes. |
HTTP asynchronous (wan2.5 and earlier models)
This API uses the old protocol and supports only wan2.5 and earlier models.
Because text-to-image tasks can take significant time (typically 1 to 2 minutes), the API uses an asynchronous call. The flow includes two core steps: Create task -> Poll for result. The process is as follows:
Processing time depends on the task queue and service status.
Step 1: Create a task and get the task ID
Beijing
POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis
Singapore
POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis
-
After the task is created, use the returned
task_idto query the result. Thetask_idis valid for 24 hours. Do not create duplicate tasks. Instead, use polling to retrieve the result. -
For guidance for beginners, see Call APIs with Postman or cURL.
Request parameters |
Text-to-image
Text-to-image (with negative prompt)Use negative_prompt to prevent "people" from appearing in the generated image.
|
Request headers |
|
|
Content-Type The content type of the request. Must be |
|
|
Authorization Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx. |
|
|
X-DashScope-Async Enables asynchronous processing. HTTP requests support only asynchronous calls. Must be Important
If this request header is missing, the error "current user api does not support synchronous calls" is returned. |
|
Request body |
|
|
model The model name. For text-to-image models, see Model List. Example: wan2.5-t2i-preview. Note
For HTTP calls to the wan2.6 model, see HTTP synchronous call and HTTP asynchronous call. |
|
|
input The input object containing the prompt. |
|
|
parameters The image generation parameters. |
Response parameters |
Successful responseSave the
Error responseTask creation failed. See Error codes.
|
|
output The task output information. |
|
|
request_id Unique request identifier for tracing and troubleshooting. |
|
|
code Error code. Returned only for failed requests. See Error codes. |
|
|
message Detailed error message. Returned only for failed requests. See Error codes. |
Step 2: Query the result by task ID
China (Beijing)
GET https://dashscope.aliyuncs.com/api/v1/tasks/{task_id}
Singapore
GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}
When calling, replace WorkspaceId with your actual workspace ID.
-
Polling recommendation: Image generation is time-consuming. Use a polling mechanism with a reasonable interval, such as 10 seconds.
-
Task state transition: PENDING → RUNNING → SUCCEEDED or FAILED.
-
Result link: After a task succeeds, an image URL valid for 24 hours is returned. Download and save the image to permanent storage, such as OSS.
-
Requests Per Second (RPS) limit: The default RPS for the query API is 20. For higher-frequency queries or event notifications, we recommend that you configure an asynchronous task callback.
-
More operations: For batch queries, task cancellation, and other operations, see Manage asynchronous tasks.
Request parameters |
Query task resultReplace If you use a model in the Singapore region, replace
|
Request headers |
|
|
Authorization Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx. |
|
URL path parameters |
|
|
task_id The ID of the task. |
Response parameters |
Successful task executionImage URLs are valid for only 24 hours and then automatically purged. Save generated images promptly. Task failedWhen a task fails,
Partial task failureThe model can generate multiple images per task. If at least one succeeds, the task status is
Task query expiredThe
|
|
output The task output information. |
|
|
usage Usage statistics for the request. Only successful results are counted. |
|
|
request_id Unique request identifier for tracing and troubleshooting. |
DashScope Python SDK
The SDK parameter names align with the HTTP API, with structures adapted for Python.
Because text-to-image tasks can take significant time, the SDK encapsulates the HTTP asynchronous call process and supports both synchronous and asynchronous calls.
Processing time depends on the task queue and service status.
wan2.6
-
The following code is only for the wan2.6 model.
-
Make sure your DashScope Python SDK version is at least 1.25.7 before you run the following code. To update, see Install the SDK.
The base_url and API key are region-specific. The following example shows a call in the Beijing region:
China (Beijing)
https://dashscope.aliyuncs.com/api/v1
Singapore
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
When calling, replace WorkspaceId with your actual workspace ID.
US (Virginia)
https://dashscope-us.aliyuncs.com/api/v1
Germany (Frankfurt)
https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1
Replace WorkspaceId with your actual Workspace ID.
The global deployment scope (Frankfurt region) supports only asynchronous calls.
Synchronous call
Request example
import os
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message
# The following is the URL for the Beijing region. The base_url is region-specific.
dashscope.base_http_api_url = 'https://dashscope.aliyuncs.com/api/v1'
# If you have not configured an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"
# The API key is region-specific. To obtain an API key: https://help.aliyun.com/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
message = Message(
role="user",
content=[
{
'text': 'A flower shop with exquisite windows, a beautiful wooden door, and flowers on display'
}
]
)
print("----Sync call, please wait a moment----")
rsp = ImageGeneration.call(
model="wan2.6-t2i",
api_key=api_key,
messages=[message],
negative_prompt="",
prompt_extend=True,
watermark=False,
n=1,
size="1280*1280"
)
print(rsp)
Response example
The URL is valid for 24 hours. You must download the image promptly.
{
"status_code": 200,
"request_id": "820dd0db-eb42-4e05-8d6a-1ddb4axxxxxx",
"code": "",
"message": "",
"output": {
"text": null,
"finish_reason": null,
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
"type": "image"
}
]
}
}
],
"audio": null,
"finished": true
},
"usage": {
"input_tokens": 0,
"output_tokens": 0,
"characters": 0,
"image_count": 1,
"size": "1280*1280",
"total_tokens": 0
}
}
Asynchronous call
Request example
import os
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Role, Message
from http import HTTPStatus
# The following is the URL for the Beijing region. The base_url is region-specific.
dashscope.base_http_api_url = 'https://dashscope.aliyuncs.com/api/v1'
# If you have not configured an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"
# The API keys for the Singapore and Beijing regions are different. To obtain an API key: https://help.aliyun.com/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
# Create an asynchronous task
def create_async_task():
print("Creating async task...")
message = Message(
role="user",
content=[{'text': 'A flower shop with exquisite windows, a beautiful wooden door, and flowers on display'}]
)
response = ImageGeneration.async_call(
model="wan2.6-t2i",
api_key=api_key,
messages=[message],
negative_prompt="",
prompt_extend=True,
watermark=False,
n=1,
size="1280*1280"
)
if response.status_code == 200:
print("Task created successfully:", response)
return response
else:
raise Exception(f"Failed to create task: {response.code} - {response.message}")
# Wait for the task to complete
def wait_for_completion(task_response):
print("Waiting for task completion...")
status = ImageGeneration.wait(task=task_response, api_key=api_key)
if status.output.task_status == "SUCCEEDED":
print("Task succeeded!")
print("Response:", status)
else:
raise Exception(f"Task failed with status: {status.output.task_status}")
# Fetch asynchronous task information
def fetch_task_status(task):
print("Fetching task status...")
status = ImageGeneration.fetch(task=task, api_key=api_key)
if status.status_code == HTTPStatus.OK:
print("Task status:", status.output.task_status)
print("Response details:", status)
else:
print(f"Failed to fetch status: {status.code} - {status.message}")
# Cancel the asynchronous task
def cancel_task(task):
print("Canceling task...")
response = ImageGeneration.cancel(task=task, api_key=api_key)
if response.status_code == HTTPStatus.OK:
print("Task canceled successfully:", response.output.task_status)
else:
print(f"Failed to cancel task: {response.code} - {response.message}")
# Main execution flow
if __name__ == "__main__":
task = create_async_task()
wait_for_completion(task)
Response example
-
Response example for creating a task
{ "status_code": 200, "request_id": "c4f11410-ea42-4996-957d-9c82f9xxxxxx", "code": "", "message": "", "output": { "text": null, "finish_reason": null, "choices": null, "audio": null, "task_id": "f470bbfd-d955-4165-935b-d35b8eexxxxxx", "task_status": "PENDING" }, "usage": { "input_tokens": 0, "output_tokens": 0, "characters": 0 } } -
Response example for querying a task result
The URL is valid for 24 hours. You must download the image promptly.
{ "status_code": 200, "request_id": "7e57e7e8-00b0-4534-9aff-fe31e0xxxxxx", "code": null, "message": "", "output": { "text": null, "finish_reason": null, "choices": [ { "finish_reason": "stop", "message": { "role": "assistant", "content": [ { "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx", "type": "image" } ] } } ], "audio": null, "task_id": "f470bbfd-d955-4165-935b-d35b8exxxxxx", "task_status": "SUCCEEDED", "submit_time": "2026-01-09 17:18:17.901", "scheduled_time": "2026-01-09 17:18:17.941", "end_time": "2026-01-09 17:18:45.544", "finished": true }, "usage": { "input_tokens": 0, "output_tokens": 0, "characters": 0, "size": "1280*1280", "total_tokens": 0, "image_count": 1 } }
wan2.5 and earlier models
-
The following code is only for wan2.5 and earlier models.
-
Make sure your DashScope Python SDK version is at least 1.25.2 before you run the following code.
If the version is too low, errors such as "url error, please check url!" may occur. To update, see Install the SDK.
The base_url and API key are region-specific. The following example shows a call in the Beijing region:
China (Beijing)
https://dashscope.aliyuncs.com/api/v1
Singapore
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
When calling, replace WorkspaceId with your actual workspace ID.
Synchronous call
Request example
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis
import os
import dashscope
# The following is the URL for the Beijing region. If you are using a model in the Singapore region, replace the URL with: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope.aliyuncs.com/api/v1'
# If you have not configured an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"
# The API keys for the Singapore and Beijing regions are different. To obtain an API key: https://help.aliyun.com/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
print('----Sync call, please wait a moment----')
rsp = ImageSynthesis.call(api_key=api_key,
model="wan2.5-t2i-preview",
prompt="A flower shop with exquisite windows, a beautiful wooden door, and flowers on display",
negative_prompt="",
n=1,
size='1280*1280',
prompt_extend=True,
watermark=False,
seed=12345)
print('response: %s' % rsp)
if rsp.status_code == HTTPStatus.OK:
# Save the image in the current directory
for result in rsp.output.results:
file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
with open('./%s' % file_name, 'wb+') as f:
f.write(requests.get(result.url).content)
else:
print('sync_call Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
Response example
The URL is valid for 24 hours. You must download the image promptly.
{
"status_code": 200,
"request_id": "9d634fda-5fe9-9968-a908-xxxxxx",
"code": null,
"message": "",
"output": {
"task_id": "d35658e4-483f-453b-b8dc-xxxxxx",
"task_status": "SUCCEEDED",
"results": [{
"url": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/1.png",
"orig_prompt": "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display",
"actual_prompt": "An exquisite flower shop, with elegant carvings on the windows and a beautiful wooden door with a brass handle. Inside, a variety of colorful flowers such as roses, tulips, and lilies are displayed. The background is a warm indoor scene with soft light, creating a peaceful and comfortable atmosphere. High-definition realistic photography, close-up center composition."
}],
"submit_time": "2025-01-08 19:36:01.521",
"scheduled_time": "2025-01-08 19:36:01.542",
"end_time": "2025-01-08 19:36:13.270",
"task_metrics": {
"TOTAL": 1,
"SUCCEEDED": 1,
"FAILED": 0
}
},
"usage": {
"image_count": 1
}
}
Asynchronous call
Request example
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis
import os
import dashscope
# The following is the URL for the Beijing region. If you are using a model in the Singapore region, replace the URL with: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope.aliyuncs.com/api/v1'
# If you have not configured an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"
# The API keys for the Singapore and Beijing regions are different. To obtain an API key: https://help.aliyun.com/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
def async_call():
print('----Create task----')
task_info = create_async_task()
print('----Wait for task to complete, then save image----')
wait_async_task(task_info)
# Create an asynchronous task
def create_async_task():
rsp = ImageSynthesis.async_call(api_key=api_key,
model="wan2.5-t2i-preview",
prompt="A flower shop with exquisite windows, a beautiful wooden door, and flowers on display",
negative_prompt="",
n=1,
size='1280*1280',
prompt_extend=True,
watermark=False,
seed=12345)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
return rsp
# Wait for the asynchronous task to finish
def wait_async_task(task):
rsp = ImageSynthesis.wait(task=task, api_key=api_key)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output)
# save file to current directory
for result in rsp.output.results:
file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
with open('./%s' % file_name, 'wb+') as f:
f.write(requests.get(result.url).content)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
# Fetch asynchronous task information
def fetch_task_status(task):
status = ImageSynthesis.fetch(task=task, api_key=api_key)
print(status)
if status.status_code == HTTPStatus.OK:
print(status.output.task_status)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(status.status_code, status.code, status.message))
# Cancel the asynchronous task. Only tasks in the PENDING state can be canceled.
def cancel_task(task):
rsp = ImageSynthesis.cancel(task=task, api_key=api_key)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output.task_status)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
if __name__ == '__main__':
async_call()
Response example
-
Response example for creating a task
{ "status_code": 200, "request_id": "31b04171-011c-96bd-ac00-f0383b669cc7", "code": "", "message": "", "output": { "task_id": "4f90cf14-a34e-4eae-xxxxxxxx", "task_status": "PENDING", "results": [] }, "usage": null } -
Response example for querying a task result
The URL is valid for 24 hours. You must download the image promptly.
{ "status_code": 200, "request_id": "9d634fda-5fe9-9968-a908-xxxxxx", "code": null, "message": "", "output": { "task_id": "d35658e4-483f-453b-b8dc-xxxxxx", "task_status": "SUCCEEDED", "results": [{ "url": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/xxx.png", "orig_prompt": "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display", "actual_prompt": "An exquisite flower shop, with elegant carvings on the windows and a beautiful wooden door with a brass handle. Inside, a variety of colorful flowers such as roses, tulips, and lilies are displayed. The background is a warm indoor scene with soft light, creating a peaceful and comfortable atmosphere. High-definition realistic photography, close-up center composition." }], "submit_time": "2025-01-08 19:36:01.521", "scheduled_time": "2025-01-08 19:36:01.542", "end_time": "2025-01-08 19:36:13.270", "task_metrics": { "TOTAL": 1, "SUCCEEDED": 1, "FAILED": 0 } }, "usage": { "image_count": 1 } }
DashScope Java SDK
The SDK parameter names align with the HTTP API, with structures adapted for Java.
Text-to-image tasks can take significant time. The SDK encapsulates the HTTP asynchronous call flow and supports both synchronous and asynchronous calls.
Processing time depends on the task queue and service status.
wan2.6
-
The following code applies only to the wan2.6-t2i model.
-
Make sure that your DashScope Java SDK version is 2.22.6 or later before you run the following code.
The base_url and API key are specific to each region and cannot be used interchangeably. The following examples show how to make a call in the Beijing region:
China (Beijing)
https://dashscope.aliyuncs.com/api/v1
Singapore
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
When calling, replace WorkspaceId with your actual workspace ID.
US (Virginia)
https://dashscope-us.aliyuncs.com/api/v1
Germany (Frankfurt)
https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1
Replace WorkspaceId with your actual Workspace ID.
The global deployment scope (Frankfurt region) supports only asynchronous calls.
Synchronous call
Request example
import com.alibaba.dashscope.aigc.imagegeneration.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.util.Collections;
public class Main {
static {
// This is the URL for the Beijing region. The base_url varies by region.
Constants.baseHttpApiUrl = "https://dashscope.aliyuncs.com/api/v1";
}
// If you have not configured the environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx"
// The API key is different for each region. To get an API key: https://help.aliyun.com/en/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void basicCall() throws ApiException, NoApiKeyException, UploadFileException {
ImageGenerationMessage message = ImageGenerationMessage.builder()
.role("user")
.content(Collections.singletonList(
Collections.singletonMap("text", "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display")
)).build();
ImageGenerationParam param = ImageGenerationParam.builder()
.apiKey(apiKey)
.model("wan2.6-t2i")
.n(1)
.size("1280*1280")
.negativePrompt("")
.promptExtend(true)
.watermark(false)
.messages(Collections.singletonList(message))
.build();
ImageGeneration imageGeneration = new ImageGeneration();
ImageGenerationResult result = null;
try {
System.out.println("---sync call, please wait a moment----");
result = imageGeneration.call(param);
} catch (ApiException | NoApiKeyException | UploadFileException e) {
throw new RuntimeException(e.getMessage());
}
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
basicCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
}
}
Response example
The URL is valid for 24 hours. You must download the image promptly.
{
"status_code": 200,
"request_id": "50b57166-eaaa-4f17-b1e0-35a5ca88672c",
"code": "",
"message": "",
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
"type": "image"
}
]
}
}
],
"finished": true
},
"usage": {
"input_tokens": 0,
"output_tokens": 0,
"image_count": 1,
"size": "1280*1280",
"total_tokens": 0
}
}
Asynchronous call
Request example
import com.alibaba.dashscope.aigc.imagegeneration.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.util.Collections;
public class Main {
static {
// This is the URL for the Beijing region. The base_url varies by region.
Constants.baseHttpApiUrl = "https://dashscope.aliyuncs.com/api/v1";
}
// If you have not configured the environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx"
// The API key is different for each region. To get an API key: https://help.aliyun.com/en/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void asyncCall() throws ApiException, NoApiKeyException, UploadFileException {
ImageGenerationMessage message = ImageGenerationMessage.builder()
.role("user")
.content(Collections.singletonList(
Collections.singletonMap("text", "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display")
)).build();
ImageGenerationParam param = ImageGenerationParam.builder()
.apiKey(apiKey)
.model("wan2.6-t2i")
.n(1)
.size("1280*1280")
.negativePrompt("")
.promptExtend(true)
.watermark(false)
.messages(Collections.singletonList(message))
.build();
ImageGeneration imageGeneration = new ImageGeneration();
ImageGenerationResult result = null;
try {
System.out.println("---async call, creating task----");
result = imageGeneration.asyncCall(param);
} catch (ApiException | NoApiKeyException | UploadFileException e) {
throw new RuntimeException(e.getMessage());
}
System.out.println(JsonUtils.toJson(result));
String taskId = result.getOutput().getTaskId();
// Wait for the task to complete
waitTask(taskId);
}
public static void waitTask(String taskId) throws ApiException, NoApiKeyException {
ImageGeneration imageGeneration = new ImageGeneration();
ImageGenerationResult result = imageGeneration.wait(taskId, apiKey);
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
asyncCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
}
}
Response examples
-
Example response for creating a task
{ "status_code": 200, "request_id": "9cd85950-2e26-4b2c-b562-1694cf9288e5", "code": "", "message": "", "output": { "task_id": "4c861fbe-af89-4a2f-8fc5-4bb15c3139ba", "task_status": "PENDING" }, "usage": null }
-
Example response for querying the task result
The URL is valid for 24 hours. You must download the image promptly.
{ "status_code": 200, "request_id": "cbdf1424-306e-4a52-82f3-8bf5d8a99103", "code": "", "message": "", "output": { "choices": [ { "finish_reason": "stop", "message": { "role": "assistant", "content": [ { "image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx", "type": "image" } ] } } ], "task_id": "4c861fbe-af89-4a2f-8fc5-4bb15c3139ba", "task_status": "SUCCEEDED", "submit_time": "2026-01-16 16:36:06.556", "scheduled_time": "2026-01-16 16:36:06.591", "end_time": "2026-01-16 16:36:25.190", "finished": true }, "usage": { "input_tokens": 0, "output_tokens": 0, "size": "1280*1280", "total_tokens": 0, "image_count": 1 } }
wan2.5 and earlier models
-
The following code applies only to wan2.5 and earlier models.
-
Make sure that your DashScope Java SDK version is 2.22.2 or later before you run the following code.
If your version is too old, errors such as "url error, please check url!" may occur. See Install the SDK to update.
The base_url and API key are specific to each region and cannot be used interchangeably. The following examples show how to make a call in the Beijing region:
China (Beijing)
https://dashscope.aliyuncs.com/api/v1
Singapore
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
When calling, replace WorkspaceId with your actual workspace ID.
Synchronous call
Request example
// Copyright (c) Alibaba, Inc. and its affiliates.
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisListResult;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.task.AsyncTaskListParam;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.util.HashMap;
import java.util.Map;
public class Main {
static {
// This is the URL for the Beijing region. If you use a model in the Singapore region, replace the URL with: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
Constants.baseHttpApiUrl = "https://dashscope.aliyuncs.com/api/v1";
}
// If you have not configured the environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx"
// The API keys for the Singapore and Beijing regions are different. To get an API key: https://help.aliyun.com/en/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void basicCall() throws ApiException, NoApiKeyException {
// Set the parameters
Map<String, Object> parameters = new HashMap<>();
parameters.put("prompt_extend", true);
parameters.put("watermark", false);
parameters.put("seed", 12345);
ImageSynthesisParam param =
ImageSynthesisParam.builder()
.apiKey(apiKey)
.model("wan2.5-t2i-preview")
.prompt("A flower shop with exquisite windows, a beautiful wooden door, and flowers on display")
.n(1)
.size("1280*1280")
.negativePrompt("")
.parameters(parameters)
.build();
ImageSynthesis imageSynthesis = new ImageSynthesis();
ImageSynthesisResult result = null;
try {
System.out.println("---sync call, please wait a moment----");
result = imageSynthesis.call(param);
} catch (ApiException | NoApiKeyException e){
throw new RuntimeException(e.getMessage());
}
System.out.println(JsonUtils.toJson(result));
}
public static void listTask() throws ApiException, NoApiKeyException {
ImageSynthesis is = new ImageSynthesis();
AsyncTaskListParam param = AsyncTaskListParam.builder().build();
param.setApiKey(apiKey);
ImageSynthesisListResult result = is.list(param);
System.out.println(result);
}
public static void fetchTask(String taskId) throws ApiException, NoApiKeyException {
ImageSynthesis is = new ImageSynthesis();
// If the DASHSCOPE_API_KEY environment variable is set, you can set apiKey to null.
ImageSynthesisResult result = is.fetch(taskId, apiKey);
System.out.println(result.getOutput());
System.out.println(result.getUsage());
}
public static void main(String[] args){
try{
basicCall();
//listTask();
}catch(ApiException|NoApiKeyException e){
System.out.println(e.getMessage());
}
}
}
Response example
The URL is valid for 24 hours. You must download the image promptly.
{
"request_id": "22f9c744-206c-9a78-899a-xxxxxx",
"output": {
"task_id": "4a0f8fc6-03fb-4c44-a13a-xxxxxx",
"task_status": "SUCCEEDED",
"results": [{
"orig_prompt": "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display",
"actual_prompt": "A flower shop with exquisitely carved windows and a beautiful dark wooden door slightly ajar. A variety of fresh flowers, including roses, lilies, and sunflowers, are on display inside, vibrant in color and fragrant. The background is a cozy indoor scene with soft light streaming through the windows onto the flowers. High-definition realistic photography, medium shot composition.",
"url": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/1.png"
}],
"task_metrics": {
"TOTAL": 1,
"SUCCEEDED": 1,
"FAILED": 0
}
},
"usage": {
"image_count": 1
}
}
Asynchronous call
Request example
// Copyright (c) Alibaba, Inc. and its affiliates.
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.util.HashMap;
import java.util.Map;
public class Main {
static {
// This is the URL for the Beijing region. If you use a model in the Singapore region, replace the URL with: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
Constants.baseHttpApiUrl = "https://dashscope.aliyuncs.com/api/v1";
}
// If you have not configured the environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx"
// The API keys for the Singapore and Beijing regions are different. To get an API key: https://help.aliyun.com/en/model-studio/get-api-key
String apiKey = System.getenv("DASHSCOPE_API_KEY");
public void asyncCall() {
System.out.println("---create task----");
String taskId = this.createAsyncTask();
System.out.println("---wait task done then return image url----");
this.waitAsyncTask(taskId);
}
/**
* Create an asynchronous task
* @return taskId
*/
public String createAsyncTask() {
// Set the parameters
Map<String, Object> parameters = new HashMap<>();
parameters.put("prompt_extend", true);
parameters.put("watermark", false);
parameters.put("seed", 12345);
ImageSynthesisParam param =
ImageSynthesisParam.builder()
.apiKey(apiKey)
.model("wan2.5-t2i-preview")
.prompt("A flower shop with exquisite windows, a beautiful wooden door, and flowers on display")
.n(1)
.size("1280*1280")
.negativePrompt("")
.parameters(parameters)
.build();
ImageSynthesis imageSynthesis = new ImageSynthesis();
ImageSynthesisResult result = null;
try {
result = imageSynthesis.asyncCall(param);
} catch (Exception e){
throw new RuntimeException(e.getMessage());
}
System.out.println(JsonUtils.toJson(result));
String taskId = result.getOutput().getTaskId();
System.out.println("taskId=" + taskId);
return taskId;
}
/**
* Wait for the asynchronous task to finish
* @param taskId The task ID
* */
public void waitAsyncTask(String taskId) {
ImageSynthesis imageSynthesis = new ImageSynthesis();
ImageSynthesisResult result = null;
try {
// After configuring the environment variable, you can set apiKey to null here
result = imageSynthesis.wait(taskId, apiKey);
} catch (ApiException | NoApiKeyException e){
throw new RuntimeException(e.getMessage());
}
System.out.println(JsonUtils.toJson(result));
System.out.println(JsonUtils.toJson(result.getOutput()));
}
public static void main(String[] args){
Main main = new Main();
main.asyncCall();
}
}
Response examples
-
Example response for creating a task
{ "request_id": "5dbf9dc5-4f4c-9605-85ea-542f97709ba8", "output": { "task_id": "7277e20e-aa01-4709-xxxxxxxx", "task_status": "PENDING" } } -
Example response for querying the task result
{ "request_id": "22f9c744-206c-9a78-899a-xxxxxx", "output": { "task_id": "4a0f8fc6-03fb-4c44-a13a-xxxxxx", "task_status": "SUCCEEDED", "results": [{ "orig_prompt": "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display", "actual_prompt": "A flower shop with exquisitely carved windows and a beautiful dark wooden door slightly ajar. A variety of fresh flowers, including roses, lilies, and sunflowers, are on display inside, vibrant in color and fragrant. The background is a cozy indoor scene with soft light streaming through the windows onto the flowers. High-definition realistic photography, medium shot composition.", "url": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/1.png" }], "task_metrics": { "TOTAL": 1, "SUCCEEDED": 1, "FAILED": 0 } }, "usage": { "image_count": 1 } }
Limitations
-
Data validity: The task
task_idand imageurlare retained for only 24 hours. After this period, they cannot be queried or downloaded. -
Content moderation: Both the input
promptand output image undergo content moderation. Non-compliant content returns anIPInfringementSuspectorDataInspectionFailederror. See Error codes.
Billing and rate limiting
-
Check free quotas and pricing in the console.
-
For model rate limiting, see Wan series.
-
Billing is based on the number of images successfully generated. Failed calls do not incur fees and do not consume the new user free quota.
Error codes
If the model call fails and returns an error message, see Error codes for resolution.
FAQ
Q: How do I view a model's inference costs and call volume?
A: See Bill inquiry and cost management.