All Products
Search
Document Center

Alibaba Cloud Model Studio:Wan - text-to-image V2 API reference

Last Updated:Mar 15, 2026

The Wan text-to-image model generates images from text and supports various artistic styles and realistic photographic effects to meet diverse creative needs.

Quick links: Try online (Singapore | Virginia | Beijing) | Wan official website

Note

This document describes the actual API capabilities, which may differ from the Wan official website features.

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.

Important

The Singapore, Virginia, and Beijing regions have separate API keys and request endpoints. Do not use them interchangeably. Cross-region calls result in authentication failures or service errors. See Select a region and deployment mode for details.

HTTP synchronous call (wan2.6)

Important

The API in this section uses a new protocol and supports only the wan2.6 model.

Retrieve the result in a single request (recommended for most scenarios).

Singapore: POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

Virginia: POST https://dashscope-us.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

Beijing: POST https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

Request parameters

Text-to-image

curl --location 'https://dashscope-intl.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": "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display"
                    }
                ]
            }
        ]
    },
    "parameters": {
        "prompt_extend": true,
        "watermark": false,
        "n": 1,
        "negative_prompt": "",
        "size": "1280*1280"
    }
}'

Request headers

Content-Type string (Required)

The content type of the request. Must be application/json.

Authorization string (Required)

The authentication credentials using a Model Studio API key.

Example: Bearer sk-xxxx

Request body

model string (Required)

The model name. Example: wan2.6-t2i.

Note

For HTTP calls on wan2.5 and earlier models, see HTTP asynchronous invocation.

input object (Required)

Basic input information.

Properties

messages array (Required)

Request content array. Only single-turn conversations supported (one set of role and content parameters).

Properties

role string (Required)

Message role. Must be set to user.

content array (Required)

Message content array.

Properties

text string (Required)

The positive prompt. It describes the content, style, and composition of the image that you want to generate.

Supports Chinese and English. Maximum 2,100 characters (each character counts as one). Excess automatically truncated.

Example: A sitting orange cat with a happy expression, lively and cute, realistic, and accurate.

Note: Pass exactly one text. Zero or multiple texts return an error.

parameters object (Optional)

Image editing parameters.

Properties

negative_prompt string (optional)

Negative prompt describing content you do not want in the image.

Supports Chinese and English. Maximum length is 500 characters. Excess characters are truncated automatically.

Example value: Low resolution, low quality, deformed limbs, deformed fingers, oversaturated colors, wax-like appearance, no facial details, overly smooth skin, AI-looking artifacts, chaotic composition, blurry or distorted text.

size string (Optional)

The resolution of the output image, in the format of width*height.

  • The default is 1280*1280.

  • The total number of pixels must be between 1280*1280 and 1440*1440, and the aspect ratio must be between 1:4 and 4:1. For example, 768*2700 is a valid resolution.

Example: 1280*1280.

Recommended resolutions for common aspect ratios

  • 1:1: 1280*1280

  • 3:4: 1104*1472

  • 4:3: 1472*1104

  • 9:16: 960*1696

  • 16:9: 1696*960

n integer (Optional)

Important

n directly affects cost (Cost = Unit price × Number of images). Confirm model pricing before calling.

The number of images to generate. The value must be an integer from 1 to 4. The default is 4.

Billing is per image. Set to 1 for testing.

prompt_extend bool (Optional)

Enable prompt rewriting. When enabled, an LLM optimizes the prompt, significantly improving results for shorter prompts but adding 3-4 seconds processing time.

  • true (default)

  • false

watermark bool (Optional)

Add a watermark in the lower-right corner with fixed text "AI-generated".

  • false (default)

  • true

seed integer (optional)

Random number seed. Valid range: [0,2147483647].

Using the same seed keeps results relatively stable. If omitted, the algorithm uses a random seed.

Note: Image generation is probabilistic. Even with the same seed, results may vary.

Response parameters

Task successful

Task data (task status and image URLs) is retained for only 24 hours and then automatically purged. Save generated images promptly.

{
    "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"
}

Abnormal Task Execution

When a task fails, the code and message fields indicate the error cause. See Error messages to resolve errors.

{
    "request_id": "a4d78a5f-655f-9639-8437-xxxxxx",
    "code": "InvalidParameter",
    "message": "num_images_per_prompt must be 1"
}

output object

The task output information.

Properties

choices array

The output content generated by the model.

Properties

finish_reason string

Reason why the task stopped (stop = completed normally).

message object

The message returned by the model.

Properties

role string

Message role. Fixed value: assistant.

content array

Properties

image string

Generated image URL in PNG format. Valid for 24 hours; download promptly.

type string

Output type. Fixed value: image.

finished boolean

Whether the task is complete (true = complete, false = in progress).

usage object

Statistics for the output. Only successful results are counted.

Properties

image_count integer

The number of images generated by the model.

size string

The resolution of the generated image. Example: 1280*1280.

input_tokens integer

Input token count. Text-to-image billed by image count; currently fixed at 0.

output_tokens integer

Output token count. Text-to-image billed by image count; currently fixed at 0.

total_tokens integer

Total token count. Text-to-image billed by image count; currently fixed at 0.

request_id string

Unique identifier for the request. Use for tracing and troubleshooting issues.

code string

The error code. Returned only when the request fails. See error codes for details.

message string

Detailed error message. Returned only when the request fails. See error codes for details.

HTTP asynchronous call (wan2.6)

Important

The API in this section uses a new protocol and supports only the wan2.6 model.

This method is suitable for scenarios that are sensitive to timeouts. The process involves two core steps: Create a task and then poll for the result. The steps are as follows:

Step 1: Create a task to get a task ID

Singapore: POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/image-generation/generation

Virginia: POST https://dashscope-us.aliyuncs.com/api/v1/services/aigc/image-generation/generation

Beijing: POST https://dashscope.aliyuncs.com/api/v1/services/aigc/image-generation/generation

Note
  • After the task is created, use the returned task_id to query the result. The task_id is valid for 24 hours. Do not create duplicate tasks. Instead, use polling to retrieve the result.

  • For a beginner's tutorial, see Use Postman or cURL.

Request parameters

Text-to-image

curl --location 'https://dashscope-intl.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": "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display"
                    }
                ]
            }
        ]
    },
    "parameters": {
        "prompt_extend": true,
        "watermark": false,
        "n": 1,
        "negative_prompt": "",
        "size": "1280*1280"
    }
}'
Request headers

Content-Type string (Required)

The content type of the request. Must be application/json.

Authorization string (Required)

The authentication credentials using a Model Studio API key.

Example: Bearer sk-xxxx

X-DashScope-Async string (Required)

Enables asynchronous processing. Must be enable as HTTP requests support only asynchronous processing.

Important

Returns "current user api does not support synchronous calls" error if not included.

Request body

model string (Required)

The model name. Example: wan2.6-t2i.

Note

For HTTP calls to wan2.5 and earlier models, see HTTP asynchronous invocation.

input object (Required)

Basic input information.

Properties

messages array (Required)

Request content array. Only single-turn conversations supported (one set of role and content parameters).

Properties

role string (Required)

Message role. Must be user.

content array (Required)

Message content array.

Properties

text string (Required)

The positive prompt. It describes the content, style, and composition of the image that you want to generate.

Chinese and English are supported. The length cannot exceed 2,100 characters. Each Chinese character, letter, number, or symbol counts as one character. Any excess is automatically truncated.

Example: A flower shop with exquisite windows, a beautiful wooden door, and flowers on display.

Note: Pass exactly one text. Zero or multiple texts return an error.

parameters object (Optional)

Image editing parameters.

Properties

negative_prompt string (optional)

Negative prompt describing content you do not want in the image.

Supports Chinese and English. Maximum length is 500 characters. Excess characters are truncated automatically.

Example value: Low resolution, low quality, deformed limbs, deformed fingers, oversaturated colors, wax-like appearance, no facial details, overly smooth skin, AI-looking artifacts, chaotic composition, blurry or distorted text.

size string (Optional)

The resolution of the output image, in the format of width*height.

  • The default value is 1280*1280.

  • The total number of pixels must be between 1280*1280 and 1440*1440, and the aspect ratio must be between 1:4 and 4:1. For example, 768*2700 is a valid resolution.

Example: 1280*1280.

Recommended resolutions for common aspect ratios

  • 1:1: 1280*1280

  • 3:4: 1104*1472

  • 4:3: 1472*1104

  • 9:16: 960*1696

  • 16:9: 1696*960

n integer (Optional)

Important

n directly affects cost (Cost = Unit price × Number of images). Confirm model pricing before calling.

The number of images to generate. The value must be an integer from 1 to 4. The default is 4.

Note: Billing is per image. Set to 1 for testing.

prompt_extend bool (Optional)

Enable prompt rewriting. When enabled, an LLM optimizes the prompt, significantly improving results for shorter prompts but adding 3-4 seconds processing time.

  • true (default)

  • false

watermark bool (Optional)

Add a watermark in the lower-right corner with fixed text "AI-generated".

  • false (default)

  • true

seed integer (optional)

Random number seed. Valid range: [0,2147483647].

Using the same seed keeps results relatively stable. If omitted, the algorithm uses a random seed.

Note: Image generation is probabilistic. Even with the same seed, results may vary.

Response parameters

Successful response

Save the task_id to query the task status and result.

{
    "output": {
        "task_status": "PENDING",
        "task_id": "0385dc79-5ff8-4d82-bcb6-xxxxxx"
    },
    "request_id": "4909100c-7b5a-9f92-bfe5-xxxxxx"
}

Error response

Task creation failed. See error codes to resolve the issue.

{
    "code": "InvalidApiKey",
    "message": "No API-key provided.",
    "request_id": "7438d53d-6eb8-4596-8835-xxxxxx"
}

output object

The task output information.

Properties

task_id string

The ID of the task. Can be used to query the task for up to 24 hours.

task_status string

The status of the task.

Enumeration

  • PENDING

  • RUNNING

  • SUCCEEDED

  • FAILED

  • CANCELED

  • UNKNOWN: Task does not exist or status is unknown

request_id string

Unique identifier for the request. Use for tracing and troubleshooting issues.

code string

The error code. Returned only when the request fails. See error codes for details.

message string

Detailed error message. Returned only when the request fails. See error codes for details.

Step 2: Query the result by task ID

Singapore: GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/{task_id}

Virginia: GET https://dashscope-us.aliyuncs.com/api/v1/tasks/{task_id}

Beijing: GET https://dashscope.aliyuncs.com/api/v1/tasks/{task_id}

Note
  • Polling suggestion: Image generation can take some time. Use a polling mechanism with a reasonable query interval, such as 10 seconds, to retrieve the result.

  • Task status transition: PENDING → RUNNING → SUCCEEDED or FAILED.

  • Result URL: After the task is successful, an image URL is returned. The URL is valid for 24 hours. After you retrieve the URL, you must immediately download and save the image to a permanent storage service, such as Object Storage Service (OSS).

Request parameters

Query task result

Replace {task_id} with the task_id value returned by the previous API call. task_id is valid for queries within 24 hours.

curl -X GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Request headers

Authorization string (Required)

The authentication credentials using a Model Studio API key.

Example: Bearer sk-xxxx

URL path parameters

task_id string (Required)

The ID of the task to query.

Response parameters

Task successful

Task data (task status and image URLs) is retained for only 24 hours and then automatically purged. Save generated images promptly.

{
    "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
    }
}

Task abnormal

If a task fails to execute for any reason, relevant information is returned. The code and message fields indicate the cause of the error. For more information, see Error messages to resolve the issue.

{
    "code": "InvalidApiKey",
    "message": "No API-key provided.",
    "request_id": "7438d53d-6eb8-4596-8835-xxxxxx"
}

output object

The task output information.

Properties

task_id string

The ID of the task. Can be used to query the task for up to 24 hours.

task_status string

The status of the task.

Enumeration

  • PENDING

  • RUNNING

  • SUCCEEDED

  • FAILED

  • CANCELED

  • UNKNOWN: Task does not exist or status is unknown

Status transitions during polling:

  • PENDING → RUNNING → SUCCEEDED or FAILED

  • First query typically returns PENDING or RUNNING

  • SUCCEEDED status includes the generated image URL in the response

  • FAILED status requires checking the error message and retrying

submit_time string

The time when the task was submitted. Time is in UTC+8. Format: YYYY-MM-DD HH:mm:ss.SSS.

scheduled_time string

The time when the task started running. Time is in UTC+8. Format: YYYY-MM-DD HH:mm:ss.SSS.

end_time string

The time when the task was completed. Time is in UTC+8. Format: YYYY-MM-DD HH:mm:ss.SSS.

finished boolean

Indicates whether the task is complete.

  • true

  • false

choices array

The output content generated by the model.

Properties

finish_reason string

The reason why the task stopped. A value of stop indicates normal completion.

message object

The message returned by the model.

Properties

role string

Message role. Fixed value: assistant.

content array

Properties

image string

Generated image URL in PNG format. Valid for 24 hours; download promptly.

type string

Output type. Fixed value: image.

usage object

Statistics for the output. Only successful results are counted.

Properties

image_count integer

The number of generated images.

size string

The resolution of the generated image. Example: 1280*1280.

input_tokens integer

Input token count. Currently fixed at 0.

output_tokens integer

Output token count. Currently fixed at 0.

total_tokens integer

Total token count. Currently fixed at 0.

request_id string

Unique identifier for the request. Use for tracing and troubleshooting issues.

code string

The error code. Returned only when the request fails. See error codes for details.

message string

Detailed error message. Returned only when the request fails. See error codes for details.

HTTP asynchronous call (wan2.5 and earlier models)

Important

This API uses the old protocol and supports only wan2.5 and earlier models.

Text-to-image tasks typically take 1-2 minutes. The API uses asynchronous invocation: Create a task, then poll for the result.

The actual time required depends on the number of tasks in the queue and the service execution status. Be patient while you retrieve the result.

Step 1: Create a task to get a task ID

Singapore: POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis

Beijing: POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis

Note
  • After the task is created, use the returned task_id to query the result. The task_id is valid for 24 hours. Do not create duplicate tasks. Instead, use polling to retrieve the result.

  • For a beginner's tutorial, see Use Postman or cURL.

Request parameters

Text-to-image

The API keys for the Singapore and Beijing regions are different. For more information, see Obtain and configure an API key
The following URL is for the Singapore region. If you use a model in the Beijing region, replace the URL with the following one: https://dashscope.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis
curl -X POST https://dashscope-intl.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": "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display"
    },
    "parameters": {
        "size": "1280*1280",
        "n": 1
    }
}'    

Text-to-image (using a negative prompt)

Use the negative_prompt parameter to prevent the "person" element from appearing in the generated image.

The API keys for the Singapore and Beijing regions are different. For more information, see Obtain and configure an API key
The following URL is for the Singapore region. If you use a model in the Beijing region, replace the URL with the following one: https://dashscope.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis
curl -X POST https://dashscope-intl.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.2-t2i-flash",
    "input": {
        "prompt": "Snowy ground, a small white chapel, aurora borealis, winter scene, soft light.",
        "negative_prompt": "person"
    },
    "parameters": {
        "size": "1024*1024",
        "n": 1
    }
}'
Request headers

Content-Type string (Required)

The content type of the request. Must be application/json.

Authorization string (Required)

The authentication credentials using a Model Studio API key.

Example: Bearer sk-xxxx

X-DashScope-Async string (Required)

Enables asynchronous processing. Must be enable as HTTP requests support only asynchronous processing.

Important

Returns "current user api does not support synchronous calls" error if not included.

Request body

model string (Required)

The model name. For text-to-image models, see the Model list.

Example: wan2.5-t2i-preview.

Note

For information about HTTP calls for the wan2.6 model, see HTTP synchronous call and HTTP asynchronous call.

input object (Required)

Basic input information (e.g., prompt).

Properties

prompt string (Required)

Positive prompt describing desired elements and visual features. Supports Chinese and English. Each Chinese character, letter, number, or symbol counts as one character. Any excess is automatically truncated. Length limits vary by model:

  • wan2.5-t2i-preview: Up to 2,000 characters.

  • wan2.2, wan2.1 series models: Up to 500 characters.

  • wanx2.0-t2i-turbo: Up to 800 characters.

Example: A sitting orange cat, with a happy expression, lively and cute, realistic and accurate.

For more information about how to use prompts, see the Text-to-image prompt guide.

negative_prompt string (Optional)

Negative prompt describing unwanted content to constrain output. Supports Chinese and English. Cannot exceed 500 characters; any excess is automatically truncated.

Example: low resolution, error, worst quality, low quality, deformed, extra fingers, or bad proportions.

parameters object (Optional)

Image editing parameters. You can set the image resolution, enable prompt rewriting, add a watermark, and more.

Properties

size string (Optional)

Output image resolution in format width*height. Defaults and constraints vary by model:

  • wan2.5-t2i-preview: The default is 1280*1280. The total number of pixels must be between 1280*1280 and 1440*1440, and the aspect ratio must be between 1:4 and 4:1. For example, 768*2700 is a valid resolution.

  • For models of version wan2.2 and earlier: The default resolution is 1024*1024. The image width and height must be within the range of [512, 1440], with a maximum resolution of 1,440×1,440. For example, a resolution of 768×2700 exceeds the single-edge limit and is not supported.

Example: 1280*1280.

Recommended resolutions for common aspect ratios

The following resolutions are for wan2.5-t2i-preview:

  • 1:1: 1280*1280

  • 3:4: 1104*1472

  • 4:3: 1472*1104

  • 9:16: 960*1696

  • 16:9: 1696*960

n integer (Optional)

Important

n directly affects cost (Cost = Unit price × Number of images). Confirm model pricing before calling.

The number of images to generate. The value must be an integer from 1 to 4. The default is 4. During testing, you can set this parameter to 1 for low-cost validation.

prompt_extend boolean (Optional)

Enable prompt rewriting. When enabled, an LLM rewrites the input prompt, significantly improving results for shorter prompts but increasing processing time.

  • true (default)

  • false

Example: true.

watermark boolean (Optional)

Add a watermark in the lower-right corner with fixed text "AI-generated".

  • false (default)

  • true

seed integer (optional)

Random number seed. Valid range: [0,2147483647].

Using the same seed keeps results relatively stable. If omitted, the algorithm uses a random seed.

Note: Image generation is probabilistic. Even with the same seed, results may vary.

Response parameters

Successful response

Save the task_id to query the task status and result.

{
    "output": {
        "task_status": "PENDING",
        "task_id": "0385dc79-5ff8-4d82-bcb6-xxxxxx"
    },
    "request_id": "4909100c-7b5a-9f92-bfe5-xxxxxx"
}

Error response

Task creation failed. See error codes to resolve the issue.

{
    "code": "InvalidApiKey",
    "message": "No API-key provided.",
    "request_id": "7438d53d-6eb8-4596-8835-xxxxxx"
}

output object

The task output information.

Properties

task_id string

The ID of the task. Can be used to query the task for up to 24 hours.

task_status string

The status of the task.

Enumeration

  • PENDING

  • RUNNING

  • SUCCEEDED

  • FAILED

  • CANCELED

  • UNKNOWN: Task does not exist or status is unknown

request_id string

Unique identifier for the request. Use for tracing and troubleshooting issues.

code string

The error code. Returned only when the request fails. See error codes for details.

message string

Detailed error message. Returned only when the request fails. See error codes for details.

Step 2: Query the result by task ID

Singapore: GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/{task_id}

Beijing: GET https://dashscope.aliyuncs.com/api/v1/tasks/{task_id}

Note
  • Polling suggestion: Image generation can take some time. Use a polling mechanism with a reasonable query interval, such as 10 seconds, to retrieve the result.

  • Task status transition: PENDING → RUNNING → SUCCEEDED or FAILED.

  • Result URL: After the task is successful, an image URL is returned. The URL is valid for 24 hours. After you retrieve the URL, you must immediately download and save the image to a permanent storage service, such as Object Storage Service (OSS).

Request parameters

Query task result

Replace 86ecf553-d340-4e21-xxxxxxxxx with the actual task ID.

API keys are region-specific. See API key documentation for details.
For models in the Beijing region, replace base_url with https://dashscope.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx
curl -X GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Request headers

Authorization string (Required)

The authentication credentials using a Model Studio API key.

Example: Bearer sk-xxxx

URL path parameters

task_id string (Required)

The ID of the task to query.

Response parameters

Task successful

Image URLs are retained for only 24 hours and then automatically purged. Save generated images promptly.

{
    "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": "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 with a brass handle. Inside, a variety of colorful and vibrant flowers, including roses, lilies, and sunflowers, are on display. The background is a warm indoor scene, with the street visible through the window. 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
    }
}

Task failed

When a task fails, task_status is set to FAILED with an error code and message. See error codes to resolve the issue.

{
    "request_id": "e5d70b02-ebd3-98ce-9fe8-759d7d7b107d",
    "output": {
        "task_id": "86ecf553-d340-4e21-af6e-xxxxxx",
        "task_status": "FAILED",
        "code": "InvalidParameter",
        "message": "xxxxxx",
        "task_metrics": {
            "TOTAL": 4,
            "SUCCEEDED": 0,
            "FAILED": 4
        }
    }
}

Partial task failure

The model can generate multiple images in a single task. If at least one image generates successfully, the task status is marked as SUCCEEDED and returns the URLs of successful images. For any images that fail to generate, the result includes a failure reason. To resolve these failures, see error codes. Only successfully generated images count toward usage statistics.

{
    "request_id": "85eaba38-0185-99d7-8d16-xxxxxx",
    "output": {
        "task_id": "86ecf553-d340-4e21-af6e-xxxxxx",
        "task_status": "SUCCEEDED",
        "results": [
            {
                "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/123/a1.png"
            },
            {
                "code": "InternalError.Timeout",
                "message": "An internal timeout error has occurred during execution, please try again later or contact service support."
            }
        ],
        "task_metrics": {
            "TOTAL": 2,
            "SUCCEEDED": 1,
            "FAILED": 1
        }
    },
    "usage": {
        "image_count": 1
    }
}

Expired task query

The task_id is valid for 24 hours. After this period, queries fail and return the following error message.

{
    "request_id": "a4de7c32-7057-9f82-8581-xxxxxx",
    "output": {
        "task_id": "502a00b1-19d9-4839-a82f-xxxxxx",
        "task_status": "UNKNOWN"
    }
}

output object

The task output information.

Properties

task_id string

The ID of the task. Can be used to query the task for up to 24 hours.

task_status string

The status of the task.

Enumeration

  • PENDING

  • RUNNING

  • SUCCEEDED

  • FAILED

  • CANCELED

  • UNKNOWN: Task does not exist or status is unknown

Status transitions during polling:

  • PENDING → RUNNING → SUCCEEDED or FAILED

  • First query typically returns PENDING or RUNNING

  • SUCCEEDED status includes the generated image URL in the response

  • FAILED status requires checking the error message and retrying

submit_time string

The time when the task was submitted. Time is in UTC+8. Format: YYYY-MM-DD HH:mm:ss.SSS.

scheduled_time string

The time when the task started running. Time is in UTC+8. Format: YYYY-MM-DD HH:mm:ss.SSS.

end_time string

The time when the task was completed. Time is in UTC+8. Format: YYYY-MM-DD HH:mm:ss.SSS.

results array of object

A list of task results, including the image URL, prompt, and error information for partially failed tasks.

Data structure

{
    "results": [
        {
            "orig_prompt": "",
            "actual_prompt": "",
            "url": ""
        },
        {
            "code": "",
            "message": ""
        }
    ]
}

Properties

orig_prompt string

The original input prompt. This is the value of the prompt request parameter.

actual_prompt string

Returns the actual optimized prompt used when prompt rewriting is enabled. Not returned when this feature is disabled.

url string

Image URL (returned only when `task_status` is SUCCEEDED). Valid for 24 hours; use to download image.

code string

The error code. Returned only when the request fails. See error codes for details.

message string

Detailed error message. Returned only when the request fails. See error codes for details.

task_metrics object

Statistics about the task results.

Properties

TOTAL integer

Total number of tasks.

SUCCEEDED integer

Number of successful tasks.

FAILED integer

Number of failed tasks.

code string

The error code. Returned only when the request fails. See error codes for details.

message string

Detailed error message. Returned only when the request fails. See error codes for details.

usage object

Statistics for the output. Only successful results are counted.

Properties

image_count integer

Number of images successfully generated by the model. Billing formula: Fee = (Number of images) × (Unit price).

request_id string

Unique identifier for the request. Use for tracing and troubleshooting issues.

DashScope Python SDK

The parameter names in the SDK are mostly consistent with those in the HTTP API. The parameter structure is encapsulated based on the features of the programming language.

Text-to-image tasks are time-consuming. The SDK encapsulates HTTP asynchronous calls and supports both synchronous and asynchronous invocation.

The actual time required depends on the number of tasks in the queue and the service execution status. Be patient while you retrieve the result.

wan2.6

Important
  • The following code is only for the wan2.6 model.

  • Requires DashScope Python SDK 1.25.7. To update, see Install the SDK.

The base_url and API key are not universal across regions. The following example shows a call in the Singapore region:

Singapore: https://dashscope-intl.aliyuncs.com/api/v1

Virginia: https://dashscope-us.aliyuncs.com/api/v1

Beijing: https://dashscope.aliyuncs.com/api/v1

Synchronous invocation

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 base_url for the Singapore region. The base_url is different for each region.
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

# If you have not configured the environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"
# The API keys for different regions are different. To obtain an API key, see https://www.alibabacloud.com/help/zh/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 invocation

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 base_url for the Singapore region. The base_url is different for each region.
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

# If you have not configured the environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"
# The API keys for different regions are different. To obtain an API key, see https://www.alibabacloud.com/help/zh/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}")

# Get 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

1. Example of a response 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
    }
}

2. Example of a response 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

Important
  • The following code is only for wan2.5 and earlier models.

  • Before you run the following code, make sure that your DashScope Python SDK version is at least 1.25.2.

    Older versions may trigger errors such as "url error, please check url!". For more information about how to update the SDK, see Install the SDK.

The base_url and API key are not universal across regions. The following example shows a call in the Singapore region:

Singapore: https://dashscope-intl.aliyuncs.com/api/v1

Beijing: https://dashscope.aliyuncs.com/api/v1

Synchronous invocation

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 Singapore region. If you use a model in the Beijing region, replace the URL with: https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

# If you have not configured the 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, see https://www.alibabacloud.com/help/zh/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 to 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 windows decorated with elegant carvings and a beautiful wooden door with a brass handle. Inside, various colorful flowers such as roses, tulips, and lilies are on display. The background is a warm indoor scene with soft light, creating a quiet 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 invocation

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 Singapore region. If you use a model in the Beijing region, replace the URL with: https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

# If you have not configured the 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, see https://www.alibabacloud.com/help/zh/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 task done 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 complete
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))


# Get 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

1. Example of a response 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
}

2. Example of a response 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 windows decorated with elegant carvings and a beautiful wooden door with a brass handle. Inside, various colorful flowers such as roses, tulips, and lilies are on display. The background is a warm indoor scene with soft light, creating a quiet 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 parameter names in the SDK are mostly consistent with those in the HTTP API. The parameter structure is encapsulated based on the features of the programming language.

Text-to-image tasks are time-consuming. The SDK encapsulates HTTP asynchronous calls and supports both synchronous and asynchronous invocation.

The actual time required depends on the number of tasks in the queue and the service execution status. Be patient while you retrieve the result.

wan2.6

Important
  • The following code is only for the wan2.6-t2i model.

  • Requires DashScope Java SDK 2.22.6.

The base_url and API key are specific to each region. The following example shows a call made from the Singapore region:

Singapore: https://dashscope-intl.aliyuncs.com/api/v1

Virginia: https://dashscope-us.aliyuncs.com/api/v1

Beijing: https://dashscope.aliyuncs.com/api/v1

Synchronous invocation

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 {
        // The following is the URL for the Singapore region. The base_url is different for each region.
        Constants.baseHttpApiUrl = "https://dashscope-intl.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 different regions are different. To obtain an API key, see https://www.alibabacloud.com/help/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", "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 invocation

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 {
        // The following is the URL for the Singapore region. The base_url is different for each region.
        Constants.baseHttpApiUrl = "https://dashscope-intl.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 different regions are different. To obtain an API key, see https://www.alibabacloud.com/help/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", "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 example

1. Example of a 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
}

2. Example of a response for querying a 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

Important
  • wan2.6-t2i model does not support Java SDK calls. The following code is only for wan2.5 and earlier models.

  • Before you run the following code, ensure that your DashScope Java SDK version is 2.22.2 or later.

    Older versions may trigger errors such as "url error, please check url!". For more information about how to update the SDK, see Install the SDK.

The base_url and API key are not universal across regions. The following example shows a call in the Singapore region:

Singapore: https://dashscope-intl.aliyuncs.com/api/v1

Beijing: https://dashscope.aliyuncs.com/api/v1

Synchronous invocation

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 {
     // The following is the URL for the Singapore region. If you use a model in the Beijing region, replace the URL with: https://dashscope.aliyuncs.com/api/v1
     Constants.baseHttpApiUrl = "https://dashscope-intl.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 obtain an API key, see https://www.alibabacloud.com/help/zh/model-studio/get-api-key
  static String apiKey = System.getenv("DASHSCOPE_API_KEY");
  
  public static void basicCall() throws ApiException, NoApiKeyException {
        // Set 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 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. 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. Inside, a variety of colorful and fragrant flowers, including roses, lilies, and sunflowers, are on display. The background is a warm indoor scene with soft light shining on the flowers through the window. 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 invocation

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 {
        // The following is the URL for the Singapore region. If you use a model in the Beijing region, replace the URL with: https://dashscope.aliyuncs.com/api/v1
        Constants.baseHttpApiUrl = "https://dashscope-intl.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 obtain an API key, see https://www.alibabacloud.com/help/zh/model-studio/get-api-key
    static 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 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 complete
     * @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 example

1. Example of a response for creating a task

{
	"request_id": "5dbf9dc5-4f4c-9605-85ea-542f97709ba8",
	"output": {
		"task_id": "7277e20e-aa01-4709-xxxxxxxx",
		"task_status": "PENDING"
	}
}

2. Example of a response for querying a 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. Inside, a variety of colorful and fragrant flowers, including roses, lilies, and sunflowers, are on display. The background is a warm indoor scene with soft light shining on the flowers through the window. 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_id and image url are retained for only 24 hours. After this period, they cannot be queried or downloaded.

  • Content moderation: The input prompt and output image are both subject to content moderation. Requests containing prohibited content result in an IPInfringementSuspect or DataInspectionFailed error. See error codes for details.

Billing and rate limiting

  • For free quota and unit price, see Model list.

  • For rate limits, see Wan.

  • Billing details: Billing is based on the number of successfully generated images. Failed model calls or processing errors do not incur fees or consume the free quota.

Error codes

If the model call fails and returns an error message, see Error messages for resolution.

FAQ

Q: How do I view the inference costs and call volume for the model?

A: For more information, see Bill query and cost management.