Wan text-to-image V2 API reference
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
NoteThe features of the Wan official website may differ from the capabilities supported by the API. This document is based on the actual capabilities of the API and is updated in a timely manner as features are released.
Model overview
| Model name | Model description | Output image format |
|---|---|---|
wan2.6-t2i | Wan 2.6 Supports freely selecting dimensions within the total pixel area and aspect ratio constraints (same as wan2.5) | Image resolution: Total pixels between [12801280, 14401440] Image aspect ratio: [1:4, 4:1] |
wan2.5-t2i-preview | Wan 2.5 preview Supports freely selecting dimensions within the total pixel area and aspect ratio constraints
| |
wan2.2-t2i-flash | Wan 2.2 Flash 50% faster than the 2.1 model | Image resolution: Both width and height between [512, 1440] pixels Image format: png |
wan2.2-t2i-plus | Wan 2.2 Plus Comprehensive improvements in 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 Plus | |
wanx2.0-t2i-turbo | Wan 2.0 Flash |
Note
- Before calling, see the list of 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. HTTP synchronous calls are not supported.
Prerequisites
Before calling, first get and configure an API key, then configure the API key as an environment variable. To call the API through an SDK, install the DashScope SDK.
ImportantThe China (Beijing), Singapore, and US (Virginia) regions have independent API keys and request endpoints. They cannot be used interchangeably. Cross-region calls will fail authentication or cause service errors. For more information, see Select a region, service deployment scope, and endpoint.
ImportantAlibaba Cloud Model Studio has launched workspace-dedicated domains for the China (Beijing) and Singapore regions, which provide superior performance and higher stability for inference requests. We recommend migrating to the new domains:
- China (Beijing) region: migrate from
https://dashscope.aliyuncs.comtohttps://{WorkspaceId}.cn-beijing.maas.aliyuncs.com - Singapore region: migrate from
https://dashscope-intl.aliyuncs.comtohttps://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com
{WorkspaceId} is your workspace ID, which you can view on the Workspace details page in the Model Studio console. The existing domains remain available.
HTTP synchronous call (wan2.6)
ImportantThe API in this section uses the new protocol and supports only the wan2.6 model.
A result is returned in a single request. The workflow is simple, and it is recommended for most scenarios.
China (Beijing)
POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
When calling, replace {WorkspaceId} with your actual workspace ID.
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://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
Request parametersRequest headersContent-Type The request content type. This parameter must be set to Authorization Request authentication. The API uses an Alibaba Cloud Model Studio API key for authentication. Example: Bearer sk-xxxx. Request bodymodel The model name. Example: wan2.6-t2i. NoteFor HTTP calls to wan2.5 and earlier models, see HTTP asynchronous call. input Basic input information. parameters Image processing parameters. | Text-to-image |
Response parametersoutput The task output information. usage Output statistics. Only successful results are counted. request_id The unique identifier of the request. It can be used for request tracing and troubleshooting. code The error code returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes. message The detailed error information returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes. | Successful task executionTask data (such as task status and image URLs) is retained for only 24 hours and is automatically cleared after it expires. Be sure to save the generated images in a timely manner. Task execution exceptionIf the task fails for any reason, relevant information is returned, and the code and message fields clearly indicate the error cause. See Error codes for troubleshooting. |
HTTP asynchronous call (wan2.6)
ImportantThe API in this section uses the new protocol and supports only the wan2.6 model.
The task workflow consists of two core steps: "Create task -> Poll for results", as follows:
Step 1: Create a task to obtain a task ID
China (Beijing)
POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation
When calling, replace {WorkspaceId} with your actual workspace ID.
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://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation
Germany (Frankfurt)
POST https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation
When calling, replace {WorkspaceId} with your actual workspace ID.
Note
- After the task is created, use the
task_idreturned by the API to query the result. The task_id is valid for 24 hours. Do not create the task repeatedly; just poll for the result. - For a beginner's guide, see Postman.
Request parametersRequest headersContent-Type The request content type. This parameter must be set to Authorization Request authentication. The API uses an Alibaba Cloud Model Studio API key for authentication. Example: Bearer sk-xxxx. X-DashScope-Async The asynchronous processing configuration parameter. HTTP requests support only asynchronous mode, and it must be set to ImportantIf this request header is missing, the error "current user api does not support synchronous calls" is returned. Request bodymodel The model name. Example: wan2.6-t2i. NoteFor HTTP calls to wan2.5 and earlier models, see HTTP asynchronous call. input Basic input information. parameters Image processing parameters. | Text-to-image |
Response parametersoutput The task output information. request_id The unique identifier of the request. It can be used for request tracing and troubleshooting. code The error code returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes. message The detailed error information returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes. | Successful responseSave the task_id for querying the task status and results. Error responseThe task failed to be created. See Error codes for troubleshooting. |
Step 2: Query results by task ID
China (Beijing)
GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}
When calling, replace {WorkspaceId} with your actual workspace 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.
US (Virginia)
GET https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/tasks/{task_id}
Germany (Frankfurt)
GET https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1/tasks/{task_id}
When calling, replace {WorkspaceId} with your actual workspace ID.
Note
- Polling recommendation: Image generation takes a long time. We recommend using a polling mechanism with a reasonable query interval (such as 10 seconds) to obtain results.
- Task status flow: PENDING (queuing) → RUNNING (processing) → SUCCEEDED (success) / FAILED (failure).
- Result link: After the task succeeds, an image link is returned, valid for 24 hours. We recommend downloading the image immediately after obtaining the link and saving it to permanent storage (such as Alibaba Cloud OSS).
- RPS limit: The default RPS of the query API is 20. For higher-frequency queries or event notifications, we recommend configuring asynchronous task callbacks.
- More operations: For operations such as batch query and task cancellation, see Manage asynchronous tasks.
Request parametersRequest headersAuthorization Request authentication. The API uses an Alibaba Cloud Model Studio API key for authentication. Example: Bearer sk-xxxx. URL path parameterstask_id The task ID. | Query task resultsReplace |
Response parametersoutput The task output information. usage Output statistics. Only successful results are counted. request_id The unique identifier of the request. It can be used for request tracing and troubleshooting. code The error code returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes. message The detailed error information returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes. | Successful task executionTask data (such as task status and image URLs) is retained for only 24 hours and is automatically cleared after it expires. Be sure to save the generated images in a timely manner. Task execution exceptionIf the task fails for any reason, relevant information is returned, and the code and message fields clearly indicate the error cause. See Error codes for troubleshooting. |
HTTP asynchronous call (wan2.5 and earlier models)
ImportantThe API in this section uses the legacy protocol and supports only wan2.5 and earlier models.
Since text-to-image tasks take a long time (usually 1-2 minutes), the API uses asynchronous calls. The workflow consists of two core steps: "Create task -> Poll for results", as follows:
The actual time depends on the number of queued tasks and service execution. Please wait patiently when obtaining results.
Step 1: Create a task to obtain a task ID
Beijing
POST https://{WorkspaceId}.cn-beijing.maas.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
Note
- After the task is created, use the
task_idreturned by the API to query the result. The task_id is valid for 24 hours. Do not create the task repeatedly; just poll for the result. - For a beginner's guide, see Postman.
Request parametersRequest headersContent-Type The request content type. This parameter must be set to Authorization Request authentication. The API uses an Alibaba Cloud Model Studio API key for authentication. Example: Bearer sk-xxxx. X-DashScope-Async The asynchronous processing configuration parameter. HTTP requests support only asynchronous mode, and it must be set to ImportantIf this request header is missing, the error "current user api does not support synchronous calls" is returned. Request bodymodel The model name. For text-to-image models, see the model list. Example: wan2.5-t2i-preview. NoteFor HTTP calls to the wan2.6 model, see HTTP synchronous call and HTTP asynchronous call. input Basic input information, such as the prompt. parameters Image processing parameters, such as setting the image resolution, enabling intelligent prompt rewriting, and adding a watermark. | Text-to-imageText-to-image (with negative prompt)Use negative_prompt to specify that the generated image should avoid the "person" element. |
Response parametersoutput The task output information. request_id The unique identifier of the request. It can be used for request tracing and troubleshooting. code The error code returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes. message The detailed error information returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes. | Successful responseSave the task_id for querying the task status and results. Error responseThe task failed to be created. See Error codes for troubleshooting. |
Step 2: Query results by task ID
China (Beijing)
GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}
When calling, replace {WorkspaceId} with your actual workspace 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.
Note
- Polling recommendation: Image generation takes a long time. We recommend using a polling mechanism with a reasonable query interval (such as 10 seconds) to obtain results.
- Task status flow: PENDING (queuing) → RUNNING (processing) → SUCCEEDED (success) / FAILED (failure).
- Result link: After the task succeeds, an image link is returned, valid for 24 hours. We recommend downloading the image immediately after obtaining the link and saving it to permanent storage (such as Alibaba Cloud OSS).
- RPS limit: The default RPS of the query API is 20. For higher-frequency queries or event notifications, we recommend configuring asynchronous task callbacks.
- More operations: For operations such as batch query and task cancellation, see Manage asynchronous tasks.
Request parametersRequest headersAuthorization Request authentication. The API uses an Alibaba Cloud Model Studio API key for authentication. Example: Bearer sk-xxxx. URL path parameterstask_id The task ID. | Query task resultsReplace
|
Response parametersoutput The task output information. usage Output statistics. Only successful results are counted. request_id The unique identifier of the request. It can be used for request tracing and troubleshooting. | Successful task executionImage URLs are retained for only 24 hours and are automatically cleared after they expire. Save the generated images in a timely manner. Task execution failedIf the task fails, task_status is set to FAILED, and the error code and information are provided. See Error codes for troubleshooting. Partial task failureThe model can generate multiple images in one task. As long as one image is successfully generated, the task status is marked as Task query expiredThe task_id query validity period is 24 hours. After it expires, the task cannot be queried, and the following error is returned. |
DashScope Python SDK calls
The SDK parameter naming is basically the same as the HTTP API, and the parameter structure is encapsulated based on language features.
Since text-to-image tasks take a long time, the SDK encapsulates the HTTP asynchronous call process and supports both synchronous and asynchronous calling methods.
The actual time depends on the number of queued tasks and service execution. Please wait patiently when obtaining results.
wan2.6
Important
- The following code is only suitable for the wan2.6 model.
- Make sure the DashScope Python SDK version is 2.0.1 or later before running the following code. For updates, see Install the SDK.
The region and API key of each region are not interchangeable. The following examples use the Beijing region:
China (Beijing)
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1
When calling, replace {WorkspaceId} with your actual workspace ID.
Singapore
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
When calling, replace {WorkspaceId} with your actual workspace ID.
US (Virginia)
https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1
Germany (Frankfurt)
https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1
When calling, replace {WorkspaceId} with your actual workspace ID.
The global deployment (Frankfurt region) supports only asynchronous calls.
Synchronous call
Request example
import os
import dashscope
# 以下为华北2(北京)地域的配置。请将 {WorkspaceId} 替换为您的百炼业务空间ID,各地域的region取值不同。
client = dashscope.Client(
# 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
# 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="cn-beijing",
)
print("----sync call, please wait a moment----")
# generate 为一步式调用(提交任务并等待完成),返回已完成的 Job
job = client.images.generate(
model="wan2.6-t2i",
prompt='一间有着精致窗户的花店,漂亮的木质门,摆放着花朵',
negative_prompt="",
prompt_extend=True,
watermark=False,
n=1,
size="1280*1280"
)
print(job)
print(job.image_urls)
Response example
The URL is valid for 24 hours. Download the image in a timely manner.
{
"request_id": "820dd0db-eb42-4e05-8d6a-1ddb4axxxxxx",
"task_id": "f470bbfd-d955-4165-935b-d35b8eexxxxxx",
"status": "SUCCEEDED",
"results": [
{
"url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx"
}
],
"usage": {
"image_count": 1,
"size": "1280*1280"
}
}
Asynchronous call
Request example
import os
import dashscope
from dashscope.v2 import DashScopeError
# 以下为华北2(北京)地域的配置。请将 {WorkspaceId} 替换为您的百炼业务空间ID,各地域的region取值不同。
client = dashscope.Client(
# 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
# 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="cn-beijing",
)
# 创建异步任务
def create_async_task():
print("Creating async task...")
job = client.images.jobs.create(
model="wan2.6-t2i",
prompt='一间有着精致窗户的花店,漂亮的木质门,摆放着花朵',
negative_prompt="",
prompt_extend=True,
watermark=False,
n=1,
size="1280*1280"
)
print("Task created successfully:", job)
return job
# 等待任务完成(指数退避轮询,任务 FAILED 或被取消时抛出 DashScopeError)
def wait_for_completion(task):
print("Waiting for task completion...")
done = client.images.jobs.wait(task)
print("Task succeeded!")
print("Response:", done)
print("Image URLs:", done.image_urls)
# 获取异步任务信息
def fetch_task_status(task):
print("Fetching task status...")
status = client.images.jobs.fetch(task)
print("Task status:", status.status)
# 取消异步任务
def cancel_task(task):
print("Canceling task...")
response = client.images.jobs.cancel(task)
print("Task canceled successfully:", response.status)
# 主执行流程
if __name__ == "__main__":
try:
task = create_async_task()
wait_for_completion(task)
except DashScopeError as e:
print(f"HTTP返回码:{e.status_code}")
print(f"错误码:{e.code}")
print(f"错误信息:{e.message}")
print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")
Response example
- Response example of creating a task
{
"request_id": "c4f11410-ea42-4996-957d-9c82f9xxxxxx",
"task_id": "f470bbfd-d955-4165-935b-d35b8eexxxxxx",
"status": "PENDING"
}
- Response example of querying the task result
The URL is valid for 24 hours. Download the image in a timely manner.
{
"request_id": "7e57e7e8-00b0-4534-9aff-fe31e0xxxxxx",
"task_id": "f470bbfd-d955-4165-935b-d35b8exxxxxx",
"status": "SUCCEEDED",
"results": [
{
"url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx"
}
],
"usage": {
"image_count": 1,
"size": "1280*1280"
}
}
wan2.5 and earlier models
Important
-
The following code is only suitable for wan2.5 and earlier models.
-
Make sure the DashScope Python SDK version is 2.0.1 or later before running the following code.
For updates, see Install the SDK.
The region and API key of each region are not interchangeable. The following examples use the Beijing region:
China (Beijing)
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1
When calling, replace {WorkspaceId} with your actual workspace ID.
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 urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
import os
import dashscope
from dashscope.v2 import DashScopeError
# 以下为华北2(北京)地域的配置。请将 {WorkspaceId} 替换为您的百炼业务空间ID,各地域的region取值不同。
client = dashscope.Client(
# 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
# 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="cn-beijing",
)
print('----sync call, please wait a moment----')
try:
# generate 为一步式调用(提交任务并等待完成),返回已完成的 Job
job = client.images.generate(
model="wan2.5-t2i-preview",
prompt="一间有着精致窗户的花店,漂亮的木质门,摆放着花朵",
negative_prompt="",
n=1,
size='1280*1280',
prompt_extend=True,
watermark=False,
seed=12345
)
print('response: %s' % job)
# 在当前目录下保存图片
for url in job.image_urls:
file_name = PurePosixPath(unquote(urlparse(url).path)).parts[-1]
with open('./%s' % file_name, 'wb+') as f:
f.write(requests.get(url).content)
except DashScopeError as e:
print(f"HTTP返回码:{e.status_code}")
print(f"错误码:{e.code}")
print(f"错误信息:{e.message}")
print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")
Response example
The URL is valid for 24 hours. Download the image in a timely manner.
{
"request_id": "9d634fda-5fe9-9968-a908-xxxxxx",
"task_id": "d35658e4-483f-453b-b8dc-xxxxxx",
"status": "SUCCEEDED",
"results": [
{
"url": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/1.png",
"orig_prompt": "一间有着精致窗户的花店,漂亮的木质门,摆放着花朵",
"actual_prompt": "一间精致的花店,窗户上装饰着优雅的雕花,漂亮的木质门上挂着铜制把手。店内摆放着各种色彩鲜艳的花朵,如玫瑰、郁金香和百合等。背景是温馨的室内场景,光线柔和,营造出宁静舒适的氛围。高清写实摄影,近景中心构图。"
}
],
"task_metrics": {
"TOTAL": 1,
"SUCCEEDED": 1,
"FAILED": 0
},
"usage": {
"image_count": 1
}
}
Asynchronous call
Request example
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
import os
import dashscope
from dashscope.v2 import DashScopeError
# 以下为华北2(北京)地域的配置。请将 {WorkspaceId} 替换为您的百炼业务空间ID,各地域的region取值不同。
client = dashscope.Client(
# 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
# 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="cn-beijing",
)
def async_call():
print('----create task----')
task_info = create_async_task()
print('----wait task done then save image----')
wait_async_task(task_info)
# 创建异步任务
def create_async_task():
job = client.images.jobs.create(
model="wan2.5-t2i-preview",
prompt="一间有着精致窗户的花店,漂亮的木质门,摆放着花朵",
negative_prompt="",
n=1,
size='1280*1280',
prompt_extend=True,
watermark=False,
seed=12345
)
print(job)
print(job.task_id, job.status)
return job
# 等待异步任务结束(指数退避轮询,任务 FAILED 或被取消时抛出 DashScopeError)
def wait_async_task(task):
done = client.images.jobs.wait(task)
print(done)
# save file to current directory
for url in done.image_urls:
file_name = PurePosixPath(unquote(urlparse(url).path)).parts[-1]
with open('./%s' % file_name, 'wb+') as f:
f.write(requests.get(url).content)
# 获取异步任务信息
def fetch_task_status(task):
status = client.images.jobs.fetch(task)
print(status)
print(status.status)
# 取消异步任务,只有处于PENDING状态的任务才可以取消
def cancel_task(task):
rsp = client.images.jobs.cancel(task)
print(rsp)
print(rsp.status)
if __name__ == '__main__':
try:
async_call()
except DashScopeError as e:
print(f"HTTP返回码:{e.status_code}")
print(f"错误码:{e.code}")
print(f"错误信息:{e.message}")
print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")
Response example
- Response example of creating a task
{
"request_id": "31b04171-011c-96bd-ac00-f0383b669cc7",
"task_id": "4f90cf14-a34e-4eae-xxxxxxxx",
"status": "PENDING"
}
- Response example of querying the task result
The URL is valid for 24 hours. Download the image in a timely manner.
{
"request_id": "9d634fda-5fe9-9968-a908-xxxxxx",
"task_id": "d35658e4-483f-453b-b8dc-xxxxxx",
"status": "SUCCEEDED",
"results": [
{
"url": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/xxx.png",
"orig_prompt": "一间有着精致窗户的花店,漂亮的木质门,摆放着花朵",
"actual_prompt": "一间精致的花店,窗户上装饰着优雅的雕花,漂亮的木质门上挂着铜制把手。店内摆放着各种色彩鲜艳的花朵,如玫瑰、郁金香和百合等。背景是温馨的室内场景,光线柔和,营造出宁静舒适的氛围。高清写实摄影,近景中心构图。"
}
],
"task_metrics": {
"TOTAL": 1,
"SUCCEEDED": 1,
"FAILED": 0
},
"usage": {
"image_count": 1
}
}
DashScope Java SDK calls
The SDK parameter naming is basically the same as the HTTP API, and the parameter structure is encapsulated based on language features.
Since text-to-image tasks take a long time, the SDK encapsulates the HTTP asynchronous call process and supports both synchronous and asynchronous calling methods.
The actual time depends on the number of queued tasks and service execution. Please wait patiently when obtaining results.
wan2.6
Important
- The following code is only suitable for the wan2.6-t2i model.
- Make sure the DashScope Java SDK version is
2.22.6or later before running the following code.
The region and API key of each region are not interchangeable. The following examples use the Beijing region:
China (Beijing)
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1
When calling, replace {WorkspaceId} with your actual workspace ID.
Singapore
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
When calling, replace {WorkspaceId} with your actual workspace ID.
US (Virginia)
https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1
Germany (Frankfurt)
https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1
When calling, replace {WorkspaceId} with your actual workspace ID.
The global deployment (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 {
// 以下为北京地域url,各地域的base_url不同
Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
}
// 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey="sk-xxx"
// 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/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", "一间有着精致窗户的花店,漂亮的木质门,摆放着花朵")
)).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. Download the image in a timely manner.
{
"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 {
// 以下为北京地域url,各地域的base_url不同
Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
}
// 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey="sk-xxx"
// 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/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", "一间有着精致窗户的花店,漂亮的木质门,摆放着花朵")
)).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();
// 等待任务完成
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 example
- Response example of 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
}
- Response example of querying the task result
The URL is valid for 24 hours. Download the image in a timely manner.
{
"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
Important
-
The following code is only suitable for wan2.5 and earlier models.
-
Make sure the DashScope Java SDK version is
2.22.2or later before running the following code.If the version is too old, errors such as "url error, please check url!" may occur. For updates, see Install the SDK.
The region and API key of each region are not interchangeable. The following examples use the Beijing region:
China (Beijing)
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1
When calling, replace {WorkspaceId} with your actual workspace ID.
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 {
// 以下为华北2(北京)地域的URL。请将 {WorkspaceId} 替换为您的百炼业务空间ID,各地域的URL不同。
Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
}
// 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey="sk-xxx"
// 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void basicCall() throws ApiException, NoApiKeyException {
// 设置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("一间有着精致窗户的花店,漂亮的木质门,摆放着花朵")
.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 set DASHSCOPE_API_KEY environment variable, apiKey can 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. Download the image in a timely manner.
{
"request_id": "22f9c744-206c-9a78-899a-xxxxxx",
"output": {
"task_id": "4a0f8fc6-03fb-4c44-a13a-xxxxxx",
"task_status": "SUCCEEDED",
"results": [{
"orig_prompt": "一间有着精致窗户的花店,漂亮的木质门,摆放着花朵",
"actual_prompt": "一间有着精致雕花窗户的花店,漂亮的深色木质门微微敞开。店内摆放着各式各样的鲜花,包括玫瑰、百合和向日葵,色彩鲜艳,香气扑鼻。背景是温馨的室内场景,光线柔和,透过窗户洒在花朵上。高清写实摄影,中景构图。",
"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 {
// 以下为华北2(北京)地域的URL。请将 {WorkspaceId} 替换为您的百炼业务空间ID,各地域的URL不同。
Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
}
// 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey="sk-xxx"
// 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/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);
}
/**
* 创建异步任务
* @return taskId
*/
public String createAsyncTask() {
// 设置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("一间有着精致窗户的花店,漂亮的木质门,摆放着花朵")
.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;
}
/**
* 等待异步任务结束
* @param taskId 任务id
* */
public void waitAsyncTask(String taskId) {
ImageSynthesis imageSynthesis = new ImageSynthesis();
ImageSynthesisResult result = null;
try {
//环境变量配置后,可在这里将apiKey设置为null
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 example
- Response example of creating a task
{
"request_id": "5dbf9dc5-4f4c-9605-85ea-542f97709ba8",
"output": {
"task_id": "7277e20e-aa01-4709-xxxxxxxx",
"task_status": "PENDING"
}
}
- Response example of 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": "一间有着精致窗户的花店,漂亮的木质门,摆放着花朵",
"actual_prompt": "一间有着精致雕花窗户的花店,漂亮的深色木质门微微敞开。店内摆放着各式各样的鲜花,包括玫瑰、百合和向日葵,色彩鲜艳,香气扑鼻。背景是温馨的室内场景,光线柔和,透过窗户洒在花朵上。高清写实摄影,中景构图。",
"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 retention: The task
task_idand imageurlare retained for only 24 hours and cannot be queried or downloaded after expiration. - Content moderation: Both the input
promptand the output image go through content safety moderation. Requests containing non-compliant content will return the "IPInfringementSuspect" or "DataInspectionFailed" error. For more information, see Error codes.
Billing and rate limiting
- For the model free quota and unit prices, see the Model Studio console.
- For model rate limits, see Wan.
- Billing description: You are billed for the number of images successfully generated. Failed model calls or processing errors incur no 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 troubleshooting.