Skip to main content

Wan text-to-image V2 API Reference

The Wan text-to-image model generates images from text, supporting various art styles and photorealistic effects to meet diverse creative needs.

Quick links:Try it online (Beijing | Singapore| Virginia) | Wan official website | Text-to-image user guide
The features on 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 will be updated in a timely manner as features evolve.

Model overview

ModelModel descriptionOutput image format
wan2.6-t2i RecommendWan2.6Supports 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]
Image format: png

wan2.5-t2i-preview RecommendWan2.5 previewSupports freely selecting dimensions within the total pixel area and aspect ratio constraints
For example, 768*2700 is supported, while versions 2.2 and earlier have a per-side limit of 1400
wan2.2-t2i-flashWan2.2 Turbo50% faster than the 2.1 modelsImage resolution: width and height both between [512, 1440] pixelsImage format: png
wan2.2-t2i-plusWan2.2 PlusSignificantly improved stability and success rate compared to the 2.1 models
wanx2.1-t2i-turboWan2.1 Turbo
wanx2.1-t2i-plusWan2.1 Plus
wanx2.0-t2i-turboWan2.0 Turbo

Prerequisites

Before calling, first obtain and configure an API Key, then configure the API Key in environment variables. To make calls through an SDK, please install the DashScope SDK.
The China (Beijing), Singapore, and US (Virginia) regions each have their own API Key and request address, which cannot be mixed. Cross-region calls will cause authentication failures or service errors. For details, see Select a region, service deployment scope, and endpoint.
Alibaba Cloud Model Studio has launched workspace-dedicated domains for the China (Beijing) and Singapore regions, which deliver superior performance and higher stability for inference requests. We recommend migrating to the new domains:
  • China (Beijing) region: Migrate from https://dashscope.aliyuncs.com to https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com
  • Singapore region: Migrate from https://dashscope-intl.aliyuncs.com to https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com
Among them, {WorkspaceId} is your workspace ID, which you can view on the Workspace Details page in the Alibaba Cloud Model Studio console. The existing domains remain available.

HTTP synchronous calls (wan2.6)

The API in this section uses the new protocol and supports only the wan2.6 model.
Results are returned in a single request with a simple workflow, recommended for most scenarios.
  • China (Beijing)
  • Singapore
  • US (Virginia)
POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generationWhen calling, replace {WorkspaceId} with your actual workspace ID.

Request parameters

Request headers
Content-Typestring(Required)The request content type. This parameter must be set to application/json.Authorizationstring(Required)Request authentication. The API uses an Alibaba Cloud Model Studio API key for authentication. Example: Bearer sk-xxxx.
Request body
model string (Required)The model name. Example: wan2.6-t2i.
For wan2.5 and earlier models, see HTTP asynchronous calls for HTTP calls.
input object (Required)Basic input information.

Properties

messages array (Required)The request content array. Currently, only single-turn conversations are supported, that is, passing one set of role and content parameters. Multi-turn conversations are not supported.

Properties

rolestring (Required)The role of the message. This parameter must be set to user.contentarray (Required)The message content array.

Properties

textstring(Required)The positive prompt, describing the desired image content, style, and composition.Supports Chinese and English, with a maximum length of 2,100 characters. Each Chinese character, letter, digit, or symbol counts as one character, and excess parts are automatically truncated.Example: A seated orange cat, with a happy expression, lively and cute, realistic and accurate.Note: Only one text can be passed. Passing none or multiple will cause an error.
parameters object (Optional)Image processing parameters.

Properties

negative_prompt string (Optional)The negative prompt, describing content you do not want in the image, to constrain the image.Supports Chinese and English, with a maximum length of 500 characters, and excess parts are automatically truncated.Example: Low resolution, low quality, deformed limbs, deformed fingers, oversaturated image, waxy look, faces without details, overly smooth, AI-generated look. Chaotic composition. Blurry, distorted text.size string (Optional)The resolution of the output image, in the format width*height.
  • The default value is 1280*1280.
  • The total pixels are between [12801280, 14401440] and the aspect ratio range is [1:4, 4:1]. For example, 768*2700 meets the requirements.
Example: 1280*1280.

Recommended resolutions for common aspect ratios

n integer (Optional)
n directly affects the cost. Cost = Unit price × Number of images. Before calling, confirm the model pricing.
The number of images to generate. The value range is 1 to 4, and the default is 4.Note: Billing is per image. For testing, we recommend setting it to 1.prompt_extend bool (Optional)Whether to enable intelligent prompt rewriting. When enabled, a large model is used to optimize the positive prompt, which significantly improves short prompts but adds 3 to 4 seconds of latency.
  • true: default value, enable intelligent rewriting.
  • false: disable intelligent rewriting.
After intelligent rewriting is enabled, the rewritten prompt may introduce copyrighted content, triggering content moderation and returning an IPInfringementSuspect or DataInspectionFailed error.If you encounter the above errors, you can set prompt_extend to false and retry. If the prompt itself directly contains copyrighted character or work names, disabling intelligent rewriting will still cause an error, and you need to modify the prompt itself.
watermark bool (Optional)Whether to add a watermark. The watermark is located in the lower-right corner of the image, with the fixed text "AI Generated".
  • false: default value, do not add a watermark.
  • true: add a watermark.
seed integer (Optional)The random number seed, with a value range of [0,2147483647].Using the same seed parameter value keeps the generated content relatively stable. If not provided, the algorithm automatically uses a random seed.Note: The model generation process is probabilistic. Even with the same seed, identical results cannot be guaranteed.
  • Text-to-image
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
    "model": "wan2.6-t2i",
    "input": {
        "messages": [
            {
                "role": "user",
                "content": [
                    {
                        "text": "一间有着精致窗户的花店,漂亮的木质门,摆放着花朵"
                    }
                ]
            }
        ]
    },
    "parameters": {
        "prompt_extend": true,
        "watermark": false,
        "n": 1,
        "negative_prompt": "",
        "size": "1280*1280"
    }
}'

Response parameters

output objectThe task output information.

Properties

choices arrayThe output content generated by the model.

Properties

finish_reason stringThe reason the task stopped. It is stop when the task stops naturally.message objectThe message returned by the model.

Properties

rolestringThe role of the message, fixed as assistant.contentarray

Properties

image stringThe URL of the generated image, in PNG format. The link is valid for 24 hours. Download and save the image in a timely manner.type stringThe output type, fixed as image.
finished booleanWhether the task has ended.
  • true: ended.
  • false: not ended.
usage objectOutput statistics. Only successful results are counted.

Properties

image_count integerThe number of generated images.size stringThe resolution of the generated image. Example: 1280*1280.input_tokens integerInput tokens. Text-to-image is billed by the number of images, and this is currently fixed at 0.output_tokens integerOutput tokens. Text-to-image is billed by the number of images, and this is currently fixed at 0.total_tokensintegerTotal tokens. Text-to-image is billed by the number of images, and this is currently fixed at 0.
request_idstringThe unique identifier of the request. It can be used for request tracing and troubleshooting.codestringThe error code returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.messagestringThe 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 execution
  • Task execution exception
Task 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.
{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "content": [
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxx.png?Expires=xxx",
                            "type": "image"
                        }
                    ],
                    "role": "assistant"
                }
            }
        ],
        "finished": true
    },
    "usage": {
        "image_count": 1,
        "input_tokens": 0,
        "output_tokens": 0,
        "size": "1280*1280",
        "total_tokens": 0
    },
    "request_id": "815505c6-7c3d-49d7-b197-xxxxx"
}

HTTP asynchronous call (wan2.6)

The 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)
  • Singapore
  • US (Virginia)
  • Germany (Frankfurt)
POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generationWhen calling, replace {WorkspaceId} with your actual workspace ID.
  • After the task is created, use the task_id returned 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 parameters

Request headers
Content-Typestring(Required)The request content type. This parameter must be set to application/json.Authorizationstring(Required)Request authentication. The API uses an Alibaba Cloud Model Studio API key for authentication. Example: Bearer sk-xxxx.X-DashScope-Asyncstring(Required)The asynchronous processing configuration parameter. HTTP requests support only asynchronous mode, and it must be set to enable.
If this request header is missing, the error "current user api does not support synchronous calls" is returned.
Request body
model string (Required)The model name. Example: wan2.6-t2i.
For HTTP calls to wan2.5 and earlier models, see HTTP asynchronous call.
input object (Required)Basic input information.

Properties

messages array (Required)The request content array. Currently, only single-turn conversations are supported, that is, passing one set of role and content parameters. Multi-turn conversations are not supported.

Properties

rolestring (Required)The role of the message. This parameter must be set to user.contentarray (Required)The message content array.

Properties

textstring(Required)The positive prompt, describing the desired image content, style, and composition.Supports Chinese and English, with a maximum length of 2,100 characters. Each Chinese character, letter, digit, or symbol counts as one character, and excess parts are automatically truncated.Example: A flower shop with exquisite windows, a beautiful wooden door, and flowers on display.Note: Only one text can be passed. Passing none or multiple will cause an error.
parameters object (Optional)Image processing parameters.

Properties

negative_prompt string (Optional)The negative prompt, describing content you do not want in the image, to constrain the image.Supports Chinese and English, with a maximum length of 500 characters, and excess parts are automatically truncated.Example: Low resolution, low quality, deformed limbs, deformed fingers, oversaturated image, waxy look, faces without details, overly smooth, AI-generated look. Chaotic composition. Blurry, distorted text.size string (Optional)The resolution of the output image, in the format width*height.
  • The default value is 1280*1280.
  • The total pixels are between [12801280, 14401440] and the aspect ratio range is [1:4, 4:1]. For example, 768*2700 meets the requirements.
Example: 1280*1280.

Recommended resolutions for common aspect ratios

n integer (Optional)
n directly affects the cost. Cost = Unit price × Number of images. Before calling, confirm the model pricing.
The number of images to generate. The value range is 1 to 4, and the default is 4.Note: Billing is per image. For testing, we recommend setting it to 1.prompt_extend bool (Optional)Whether to enable intelligent prompt rewriting. When enabled, a large model is used to optimize the positive prompt, which significantly improves results for short prompts, but adds 3-4 seconds of processing time.
  • true: default value, enable intelligent rewriting.
  • false: disable intelligent rewriting.
After intelligent rewriting is enabled, the rewritten prompt may introduce copyrighted content, triggering content moderation and returning an IPInfringementSuspect or DataInspectionFailed error.If you encounter the above errors, you can set prompt_extend to false and retry. If the prompt itself directly contains copyrighted character or work names, disabling intelligent rewriting will still cause an error, and you need to modify the prompt itself.
watermark bool (Optional)Whether to add a watermark. The watermark is located in the lower-right corner of the image, with the fixed text "AI Generated".
  • false: default value, do not add a watermark.
  • true: add a watermark.
seed integer (Optional)The random number seed, with a value range of [0,2147483647].Using the same seed parameter value keeps the generated content relatively stable. If not provided, the algorithm automatically uses a random seed.Note: The model generation process is probabilistic. Even with the same seed, identical results cannot be guaranteed.
  • Text-to-image
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'X-DashScope-Async: enable' \
--data '{
    "model": "wan2.6-t2i",
    "input": {
        "messages": [
            {
                "role": "user",
                "content": [
                    {
                        "text": "一间有着精致窗户的花店,漂亮的木质门,摆放着花朵"
                    }
                ]
            }
        ]
    },
    "parameters": {
        "prompt_extend": true,
        "watermark": false,
        "n": 1,
        "negative_prompt": "",
        "size": "1280*1280"
    }
}'

Response parameters

output objectThe task output information.

Properties

task_id stringThe task ID. The query validity period is 24 hours.task_status stringThe task status.

Enumerated values

  • PENDING: The task is queuing
  • RUNNING: The task is being processed
  • SUCCEEDED: The task executed successfully
  • FAILED: The task failed
  • CANCELED: The task has been canceled
  • UNKNOWN: The task does not exist or its status is unknown
request_idstringThe unique identifier of the request. It can be used for request tracing and troubleshooting.codestringThe error code returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.messagestringThe detailed error information returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.
  • Successful response
  • Error response
Save the task_id for querying the task status and results.
{
    "output": {
        "task_status": "PENDING",
        "task_id": "0385dc79-5ff8-4d82-bcb6-xxxxxx"
    },
    "request_id": "4909100c-7b5a-9f92-bfe5-xxxxxx"
}

Step 2: Query results by task ID

  • China (Beijing)
  • Singapore
  • US (Virginia)
  • Germany (Frankfurt)
GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}When calling, replace {WorkspaceId} with your actual workspace ID.
  • Polling recommendations: Image generation is time-consuming. We recommend using a polling mechanism with a reasonable query interval (for example, 10 seconds) to obtain results.
  • Task status transitions: PENDING (Queuing) → RUNNING (Processing) → SUCCEEDED (Success) / FAILED (Failed).
  • Result links: The image URL is returned after the task succeeds and is valid for 24 hours. We recommend downloading the image immediately after obtaining the URL and storing it in permanent storage (such as Alibaba Cloud OSS).
  • RPS limits: 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 queries and task cancellation, see Manage asynchronous tasks.

Request parameters

Request headers
Authorizationstring(Required)Request authentication. The API uses an Alibaba Cloud Model Studio API key for authentication. Example: Bearer sk-xxxx.
URL path parameters
task_id string(Required)The task ID.
  • Query task results
Replace {task_id} entirely with the task_id value returned by the API in the previous step. The task_id query validity period is 24 hours. Also replace {WorkspaceId} with your actual workspace ID.
curl -X GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"

Response parameters

output objectThe task output information.

Properties

task_id stringThe task ID. The query validity period is 24 hours.task_status stringThe task status.

Enumerated values

  • PENDING: The task is queuing
  • RUNNING: The task is being processed
  • SUCCEEDED: The task executed successfully
  • FAILED: The task failed
  • CANCELED: The task has been canceled
  • UNKNOWN: The task does not exist or its status is unknown
Status flow during polling:
  • PENDING (queuing) → RUNNING (processing) → SUCCEEDED (success) / FAILED (failure).
  • The status of the first query is usually PENDING (queuing) or RUNNING (processing).
  • When the status changes to SUCCEEDED, the response contains the generated image URL.
  • If the status is FAILED, check the error information and retry.
submit_time stringThe task submission time. Format: YYYY-MM-DD HH:mm:ss.SSS.scheduled_time stringThe task execution time. Format: YYYY-MM-DD HH:mm:ss.SSS.end_time stringThe task completion time. Format: YYYY-MM-DD HH:mm:ss.SSS.finished booleanWhether the task has ended.
  • true: ended.
  • false: not ended.
choices arrayThe output content generated by the model.

Properties

finish_reason stringThe reason the task stopped. It is stop when the task completes normally.message objectThe message returned by the model.

Properties

rolestringThe role of the message, fixed as assistant.contentarray

Properties

image stringThe URL of the generated image, in PNG format.The link is valid for 24 hours. Download and save the image in a timely manner.type stringThe output type, fixed as image.
usage objectOutput statistics. Only successful results are counted.

Properties

image_count integerThe number of generated images.size stringThe resolution of the generated image. Example: 1280*1280.input_tokens integerThe number of input tokens. Currently fixed at 0.output_tokens integerThe number of output tokens. Currently fixed at 0.total_tokensintegerThe total number of tokens. Currently fixed at 0.
request_idstringThe unique identifier of the request. It can be used for request tracing and troubleshooting.codestringThe error code returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.messagestringThe 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 execution
  • Task execution exception
Task 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.
{
    "request_id": "2ddf53fa-699a-4267-9446-xxxxxx",
    "output": {
        "task_id": "3cd3fa4e-53ee-4136-9cab-xxxxxx",
        "task_status": "SUCCEEDED",
        "submit_time": "2025-12-18 20:03:01.802",
        "scheduled_time": "2025-12-18 20:03:01.834",
        "end_time": "2025-12-18 20:03:29.260",
        "finished": true,
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxx.png?Expires=xxx",
                            "type": "image"
                        }
                    ]
                }
            }
        ]
    },
    "usage": {
        "size": "1280*1280",
        "total_tokens": 0,
        "image_count": 1,
        "output_tokens": 0,
        "input_tokens": 0
    }
}

HTTP asynchronous call (wan2.5 and earlier models)

The 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
  • Singapore
POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis
  • After the task is created, use the task_id returned 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 parameters

Request headers
Content-Typestring(Required)The request content type. This parameter must be set to application/json.Authorizationstring(Required)Request authentication. The API uses an Alibaba Cloud Model Studio API key for authentication. Example: Bearer sk-xxxx.X-DashScope-Asyncstring(Required)The asynchronous processing configuration parameter. HTTP requests support only asynchronous mode, and it must be set to enable.
If this request header is missing, the error "current user api does not support synchronous calls" is returned.
Request body
model string (Required)The model name. For text-to-image models, see the model list.Example: wan2.5-t2i-preview.
For HTTP calls to the wan2.6 model, see HTTP synchronous call and HTTP asynchronous call.
input object (Required)Basic input information, such as the prompt.

Properties

prompt string (Required)The positive prompt, describing the elements and visual features you want in the generated image.Supports Chinese and English. Each Chinese character/letter/punctuation mark occupies one character, and excess parts are automatically truncated. The length limit varies by model version:
  • wan2.5-t2i-preview: The length must not exceed 2,000 characters.
  • wan2.2 and wan2.1 series models: The length must not exceed 500 characters.
  • wanx2.0-t2i-turbo: The length must not exceed 800 characters.
Example: A seated orange cat, with a happy expression, lively and cute, realistic and accurate.For prompt writing tips, see the Text-to-image prompt guide.negative_prompt string (Optional)The negative prompt, describing content you do not want in the image, to constrain the image.Supports Chinese and English, with a maximum length of 500 characters, and excess parts are automatically truncated.Example: Low resolution, errors, worst quality, low quality, incomplete, extra fingers, bad proportions, etc.
parameters object (Optional)Image processing parameters, such as setting the image resolution, enabling intelligent prompt rewriting, and adding a watermark.

Properties

size string (Optional)The resolution of the output image, in the format width*height. The default value and constraints vary by model version:
  • wan2.5-t2i-preview: The default value is 1280*1280. The total pixels are between [12801280, 14401440] and the aspect ratio range is [1:4, 4:1]. For example, 768*2700 meets the requirements.
  • wan2.2 and earlier models: The default value is 1024*1024. The image width and height are between [512, 1440], and the maximum resolution is 14401440. For example, 7682700 exceeds the single-side limit and is not supported.
Example: 1280*1280.

Recommended resolutions for common aspect ratios

n integer (Optional)
n directly affects the cost. Cost = Unit price × Number of images. Before calling, confirm the model pricing.
The number of images to generate. The value range is 1 to 4, and the default is 4. During testing, we recommend setting it to 1 for low-cost verification.prompt_extendboolean (Optional)Whether to enable intelligent prompt rewriting. When enabled, a large model intelligently rewrites the input prompt. It significantly improves generation results for short prompts, but increases processing time.
  • true: default value, enable intelligent rewriting.
  • false: disable intelligent rewriting.
Example: true.
After intelligent rewriting is enabled, the rewritten prompt may introduce copyrighted content, triggering content moderation and returning an IPInfringementSuspect or DataInspectionFailed error.If you encounter the above errors, you can set prompt_extend to false and retry. If the prompt itself directly contains copyrighted character or work names, disabling intelligent rewriting will still cause an error, and you need to modify the prompt itself.
watermark boolean (Optional)Whether to add a watermark. The watermark is located in the lower-right corner of the image, with the fixed text "AI Generated".
  • false: default value, do not add a watermark.
  • true: add a watermark.
seed integer (Optional)The random number seed, with a value range of [0,2147483647].Using the same seed parameter value keeps the generated content relatively stable. If not provided, the algorithm automatically uses a random seed.Note: The model generation process is probabilistic. Even with the same seed, identical results cannot be guaranteed.
  • Text-to-image
  • Text-to-image (with negative prompt)
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "wan2.5-t2i-preview",
    "input": {
        "prompt": "一间有着精致窗户的花店,漂亮的木质门,摆放着花朵"
    },
    "parameters": {
        "size": "1280*1280",
        "n": 1
    }
}'

Response parameters

output objectThe task output information.

Properties

task_id stringThe task ID. The query validity period is 24 hours.task_status stringThe task status.

Enumerated values

  • PENDING: The task is queuing
  • RUNNING: The task is being processed
  • SUCCEEDED: The task executed successfully
  • FAILED: The task failed
  • CANCELED: The task has been canceled
  • UNKNOWN: The task does not exist or its status is unknown
request_idstringThe unique identifier of the request. It can be used for request tracing and troubleshooting.codestringThe error code returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.messagestringThe detailed error information returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.
  • Successful response
  • Error response
Save the task_id for querying the task status and results.
{
    "output": {
        "task_status": "PENDING",
        "task_id": "0385dc79-5ff8-4d82-bcb6-xxxxxx"
    },
    "request_id": "4909100c-7b5a-9f92-bfe5-xxxxxx"
}

Step 2: Query results by task ID

  • China (Beijing)
  • Singapore
GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}When calling, replace {WorkspaceId} with your actual workspace ID.
  • Polling recommendations: Image generation is time-consuming. We recommend using a polling mechanism with a reasonable query interval (for example, 10 seconds) to obtain results.
  • Task status transitions: PENDING (Queuing) → RUNNING (Processing) → SUCCEEDED (Success) / FAILED (Failed).
  • Result links: The image URL is returned after the task succeeds and is valid for 24 hours. We recommend downloading the image immediately after obtaining the URL and storing it in permanent storage (such as Alibaba Cloud OSS).
  • RPS limits: 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 queries and task cancellation, see Manage asynchronous tasks.

Request parameters

Request headers
Authorizationstring(Required)Request authentication. The API uses an Alibaba Cloud Model Studio API key for authentication. Example: Bearer sk-xxxx.
URL path parameters
task_id string(Required)The task ID.
  • Query task results
Replace 86ecf553-d340-4e21-xxxxxxxxx with your actual task_id.
If you use a model in the Singapore region, replace the base_url with https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx, where {WorkspaceId} must be replaced with your actual workspace ID.
curl -X GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"

Response parameters

outputobjectThe task output information.

Properties

task_id stringThe task ID. The query validity period is 24 hours.task_status stringThe task status.

Enumerated values

  • PENDING: The task is queuing
  • RUNNING: The task is being processed
  • SUCCEEDED: The task executed successfully
  • FAILED: The task failed
  • CANCELED: The task has been canceled
  • UNKNOWN: The task does not exist or its status is unknown
Status flow during polling:
  • PENDING (queuing) → RUNNING (processing) → SUCCEEDED (success) / FAILED (failure).
  • The status of the first query is usually PENDING (queuing) or RUNNING (processing).
  • When the status changes to SUCCEEDED, the response contains the generated image URL.
  • If the status is FAILED, check the error information and retry.
submit_time stringThe task submission time. Format: YYYY-MM-DD HH:mm:ss.SSS.scheduled_time stringThe task execution time. Format: YYYY-MM-DD HH:mm:ss.SSS.end_time stringThe task completion time. Format: YYYY-MM-DD HH:mm:ss.SSS.results array of objectThe task result list, including image URLs, the prompt, and error information for partially failed tasks.
{
    "results": [
        {
            "orig_prompt": "",
            "actual_prompt": "",
            "url": ""
        },
        {
            "code": "",
            "message": ""
        }
    ]
}

Properties

orig_prompt stringThe original input prompt, corresponding to the request parameter prompt.actual_prompt stringThe optimized prompt actually used, returned when intelligent prompt rewriting is enabled. If this feature is not enabled, this field is not returned.url stringThe image URL address. It is returned only when task_status is SUCCEEDED. The link is valid for 24 hours, and you can download the image through this URL.codestringThe error code returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.messagestringThe detailed error information returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.
task_metrics objectThe task result statistics.

Properties

TOTAL integerThe total number of tasks.SUCCEEDED integerThe number of tasks with a success status.FAILED integerThe number of tasks with a failure status.
codestringThe error code returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.messagestringThe detailed error information returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.
usage objectOutput statistics. Only successful results are counted.

Properties

image_count integerThe number of images successfully generated by the model. Billing formula: Cost = Number of images × Unit price.
request_idstringThe unique identifier of the request. It can be used for request tracing and troubleshooting.
  • Successful task execution
  • Task execution failed
  • Partial task failure
  • Task query expired
Image URLs are retained for only 24 hours and are automatically cleared after they expire. Save the generated images in a timely manner.
{
    "request_id": "f767d108-7d50-908b-a6d9-xxxxxx",
    "output": {
        "task_id": "d492bffd-10b5-4169-b639-xxxxxx",
        "task_status": "SUCCEEDED",
        "submit_time": "2025-01-08 16:03:59.840",
        "scheduled_time": "2025-01-08 16:03:59.863",
        "end_time": "2025-01-08 16:04:10.660",
        "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
    }
}

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

  • 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)
  • Singapore
  • US (Virginia)
  • Germany (Frankfurt)
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1When calling, replace {WorkspaceId} with your actual workspace ID.
The global deployment (Frankfurt region) supports only asynchronous calls.
  • Synchronous call
  • Asynchronous 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"
    }
}

wan2.5 and earlier models

  • 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)
  • Singapore
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1When calling, replace {WorkspaceId} with your actual workspace ID.
  • Synchronous call
  • Asynchronous call
Request example
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
import os
import dashscope
from dashscope 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
    }
}

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

  • The following code is only suitable for the wan2.6-t2i model.
  • Make sure the DashScope Java SDK version is 2.22.6 or 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)
  • Singapore
  • US (Virginia)
  • Germany (Frankfurt)
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1When calling, replace {WorkspaceId} with your actual workspace ID.
The global deployment (Frankfurt region) supports only asynchronous calls.
  • Synchronous call
  • 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 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
    }
}

wan2.5 and earlier models

  • The following code is only suitable for wan2.5 and earlier models.
  • Make sure the DashScope Java SDK version is 2.22.2 or 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)
  • Singapore
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1When calling, replace {WorkspaceId} with your actual workspace ID.
  • Synchronous call
  • Asynchronous 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
    }
}

Limitations

  • Data retention: The task task_id and image url are retained for only 24 hours and cannot be queried or downloaded after expiration.
  • Content moderation: Both the input prompt and 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.