All Products
Search
Document Center

Alibaba Cloud Model Studio:Wanx text-to-image V2 API Reference

Last Updated:Nov 20, 2026

The Wanx text-to-image model generates images from text prompts, supporting a variety of artistic styles and photorealistic photography effects to meet diverse creative needs.

Quick entry:Try it online (Singapore | Virginia | Beijing) | Wanx official website

NoteThe features of the Wanx 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 kept in sync as features are updated.

Prerequisites

Before making calls, first obtain and configure an API Key, and then configure the API Key as an environment variable. To make calls through the SDK, please install the DashScope SDK.

ImportantThe Singapore, United States (Virginia), and China (Beijing) regions have their own dedicated API Key and request address, which cannot be mixed. Cross-region calls will cause authentication failures or service errors. For more information, see Regions, service deployment scope, and endpoints.

ImportantAlibaba Cloud Model Studio has launched workspace-specific domain names for the China (Beijing) and Singapore regions, which deliver superior performance and higher stability for inference requests. We recommend that you migrate to the new domain names:

  • 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

In this formula, {WorkspaceId} is your workspace ID, which you can view on the Workspace Details page in the Alibaba Cloud Model Studio console. The existing domain names remain available.

HTTP synchronous call (wan2.6)

ImportantThe APIs in this section use the new protocol and support only the wan2.6 model.

You can obtain the result with a single request, making the process simple. It is recommended for most scenarios.

Singapore

POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

When making calls, replace {WorkspaceId} with your actual Workspace ID.

United States (Virginia)

POST https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

China (Beijing)

POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

When making calls, replace {WorkspaceId} with your actual Workspace ID.

The global deployment scope (Frankfurt region) supports only asynchronous calls.

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 value: Bearer sk-xxxx.

Request body

model string (Required)

Model name. Example value: wan2.6-t2i.

NoteFor models of wan2.5 and earlier versions, see HTTP asynchronous calls for HTTP invocation.

input object (Required)

Basic input information.

Property

messages array (Required)

The request content array. Currently, only single-round conversations are supported, that is, one set of role and content parameters is passed in, and multi-round conversations are not supported.

Property

rolestring (Required)

The role of the message. This parameter must be set to user.

contentarray (Required)

The message content array.

Property

textstring(Required)

The positive prompt, used to describe the content, style, and composition of the image you want to generate.

Both Chinese and English are supported, with a length of no more than 2100 characters. Each Chinese character, letter, digit, or symbol counts as one character, and any excess is automatically truncated.

Example value: a sitting orange cat with a pleasant expression, lively and cute, realistic and accurate.

Note: Only one text can be passed in. Passing in none or multiple will cause an error.

parameters object (Optional)

Image processing parameters.

Property

negative_prompt string (Optional)

The negative prompt, used to describe the content that you do not want to appear in the image, constraining the picture.

Both Chinese and English are supported, with a length of no more than 500 characters. Any excess will be automatically truncated.

Example value: low resolution, low quality, deformed limbs, deformed fingers, oversaturated picture, waxy look, faces without details, overly smooth, AI-looking picture. Chaotic composition. Blurred, 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 is between [12801280, 14401440] and the aspect ratio is in the range of [1:4, 4:1]. For example, 768*2700 meets the requirements.

Example value: 1280*1280.

n integer (Optional)

Importantn directly affects the fee. Fee = Unit price × Number of images. Please confirm the Model Price before making a call.

The number of images to generate. The value ranges from 1~4, and the default is 4.

Note: Billing is based on the number of images. For testing, we recommend that you set this parameter to 1.

prompt_extend bool (Optional)

Whether to enable intelligent prompt rewriting. After this feature is enabled, a large model is used to optimize the positive prompt, which significantly improves short prompts but adds 3 to 4 seconds of processing time.

  • true: Default value. Intelligent rewriting is enabled.
  • false: Intelligent rewriting is disabled.

NoteAfter intelligent rewriting is enabled, the rewritten prompt may introduce copyrighted content, which triggers content moderation and returns the IPInfringementSuspect or DataInspectionFailed error.

If you encounter the preceding errors, set prompt_extend to false and try again. If the prompt itself directly contains the name of a copyrighted character or work, the error persists even after intelligent rewriting is disabled, and you must modify the prompt itself.

watermark bool (Optional)

Whether to add a watermark. The watermark is located in the lower-right corner of the image, and the text is fixed to “AI-generated”.

  • false: Default value. No watermark is added.
  • true: A watermark is added.

seed integer (Optional)

The random number seed. Value range: [0,2147483647].

Using the same seed parameter value keeps the generated content relatively stable. If this parameter is not specified, the algorithm automatically uses a random number seed.

Note: The model generation process is probabilistic. Even if the same seed is used, the generation results are not guaranteed to be exactly the same each time.

text-to-image

curl --location 'https://{WorkspaceId}.ap-southeast-1.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 object

Task output information.

Property

choices array

The output content generated by the model.

Property

finish_reason string

The reason why the task stopped. The value is stop when the task stops naturally.

message object

The message returned by the model.

Property

rolestring

The role of the message, which is fixed to assistant.

contentarray

Property

image string

The URL of the generated image. The image format is PNG. The link is valid for 24 hours. Download and save the image in a timely manner.

type string

The type of the output, which is fixed to image.

finished boolean

Whether the task has ended.

  • true: The task has ended.
  • false: The task has not ended.

usage object

The statistics of the output information. Only successful results are counted.

Property

image_count integer

The number of generated images.

size string

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

input_tokens integer

The input tokens. Text-to-image is billed by the number of images, and this value is currently fixed to 0.

output_tokens integer

The output tokens. Text-to-image is billed by the number of images, and this value is currently fixed to 0.

total_tokensinteger

The total tokens. Text-to-image is billed by the number of images, and this value is currently fixed to 0.

request_idstring

The unique request identifier. It can be used for request detail tracing and troubleshooting.

codestring

The error code returned when the request fails. This parameter is not returned when the request succeeds. For details, see Error codes.

messagestring

The detailed error information returned when the request fails. This parameter is not returned when the request succeeds. For details, see Error codes.

Task executed successfully

Task data (such as task status and image URLs) is retained for only 24 hours and is automatically cleared after it expires. Please 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"
}

Task execution exception

If the task fails for any reason, the relevant information will be returned, and the code and message fields clearly indicate the cause of the error. See Error codes for troubleshooting.

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

HTTP asynchronous calls (wan2.6)

ImportantThe APIs in this section use the new protocol and support only the wan2.6 model.

The task workflow consists of two core steps: "create task -> poll for results", as described below:

Step 1: Create a task to obtain the task ID

Singapore

POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation

When making calls, replace {WorkspaceId} with your actual Workspace ID.

United States (Virginia)

POST https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation

China (Beijing)

POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation

When making calls, replace {WorkspaceId} with your actual Workspace ID.

Germany (Frankfurt)

POST https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation

When making calls, replace {WorkspaceId} with your actual Workspace ID.

Note

  • After the task is created successfully, use the task_id returned by the API to query the result. The task_id is valid for 24 hours. Do not create duplicate tasks; simply poll for the results.
  • 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 value: Bearer sk-xxxx.

X-DashScope-Asyncstring(required)

The asynchronous processing configuration parameter. HTTP requests support asynchronous calls only, and it must be set toenable.

ImportantIf this request header is missing, the following error is returned: "current user api does not support synchronous calls".

Request body

model string (Required)

Model name. Example value: wan2.6-t2i.

NoteFor models of wan2.5 and earlier versions, see HTTP asynchronous calls for HTTP invocation.

input object (Required)

Basic input information.

Property

messages array (Required)

The request content array. Currently, only single-round conversations are supported, that is, one set of role and content parameters is passed in, and multi-round conversations are not supported.

Property

rolestring (Required)

The role of the message. This parameter must be set to user.

contentarray (Required)

The message content array.

Property

textstring(Required)

The positive prompt, used to describe the content, style, and composition of the image you want to generate.

Both Chinese and English are supported, with a length of no more than 2100 characters. Each Chinese character, letter, digit, or symbol counts as one character, and any excess is automatically truncated.

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

Note: Only one text can be passed in. Passing in none or multiple will cause an error.

parameters object (Optional)

Image processing parameters.

Property

negative_prompt string (Optional)

The negative prompt, used to describe the content that you do not want to appear in the image, constraining the picture.

Both Chinese and English are supported, with a length of no more than 500 characters. Any excess will be automatically truncated.

Example value: low resolution, low quality, deformed limbs, deformed fingers, oversaturated picture, waxy look, faces without details, overly smooth, AI-looking picture. Chaotic composition. Blurred, 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 is between [12801280, 14401440] and the aspect ratio is in the range of [1:4, 4:1]. For example, 768*2700 meets the requirements.

Example value: 1280*1280.

n integer (Optional)

Importantn directly affects the fee. Fee = Unit price × Number of images. Please confirm the Model Price before making a call.

The number of images to generate. The value ranges from 1~4, and the default is 4.

Note: Billing is based on the number of images. For testing, we recommend that you set this parameter to 1.

prompt_extend bool (Optional)

Whether to enable intelligent prompt rewriting. When enabled, a large language model is used to optimize the positive prompt, which significantly improves short prompts but adds 3 to 4 seconds of processing time.

  • true: The default value. Intelligent rewriting is enabled.
  • false: Intelligent rewriting is disabled.

NoteAfter intelligent rewriting is enabled, the rewritten prompt may introduce copyrighted content, which triggers content moderation and returns the IPInfringementSuspect or DataInspectionFailed error.

If you encounter the preceding errors, set prompt_extend to false and try again. If the prompt itself directly contains the name of a copyrighted character or work, the error persists even after intelligent rewriting is disabled, and you must modify the prompt itself.

watermark bool (Optional)

Whether to add a watermark. The watermark is located in the lower-right corner of the image, and the text is fixed to “AI-generated”.

  • false: Default value. No watermark is added.
  • true: A watermark is added.

seed integer (Optional)

The random number seed. Value range: [0,2147483647].

Using the same seed parameter value keeps the generated content relatively stable. If this parameter is not specified, the algorithm automatically uses a random number seed.

Note: The model generation process is probabilistic. Even if the same seed is used, the generation results are not guaranteed to be exactly the same each time.

text-to-image

curl --location 'https://{WorkspaceId}.ap-southeast-1.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 object

Task output information.

Property

task_id string

The task ID. It is valid for queries for 24 hours.

task_status string

The task status.

Enum 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_idstring

The unique request identifier. It can be used for request detail tracing and troubleshooting.

codestring

The error code returned when the request fails. This parameter is not returned when the request succeeds. For details, see Error codes.

messagestring

The detailed error information returned when the request fails. This parameter is not returned when the request succeeds. For details, see Error codes.

Success response

Save the task_id, which is used to query the task status and results.

{
    "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 for troubleshooting.

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

Step 2: Query the result by task ID

Singapore

GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}

When making calls, replace {WorkspaceId} with your actual Workspace ID.

United States (Virginia)

GET https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/tasks/{task_id}

China (Beijing)

GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}

When making calls, replace {WorkspaceId} with your actual Workspace ID.

Germany (Frankfurt)

GET https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1/tasks/{task_id}

When making calls, replace {WorkspaceId} with your actual Workspace ID.

Note

  • Polling recommendations: Image generation takes a long time. We recommend that you use a polling mechanism and set an appropriate query interval (for example, 10 seconds) to obtain the results.
  • Status transitions: PENDING (Queuing) → RUNNING (Processing) → SUCCEEDED (Success) / FAILED (Failed).
  • Result URL: After the task succeeds, the image URL is returned and is valid for 24 hours. We recommend that you download the image immediately after you obtain the URL and store it in permanent storage (such as Alibaba Cloud OSS).

Request parameters

Request headers

Authorizationstring(Required)

Request authentication. The API uses an Alibaba Cloud Model Studio API Key for authentication. Example value: Bearer sk-xxxx.

URL path parameters

task_id string(required)

The task ID.

Query task result

Replace {task_id} entirely with the value of task_id returned by the API in the previous step. The task_id can be queried within 24 hours. Also, replace {WorkspaceId} with the actual workspace ID.

curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"

Response parameters

output object

Task output information.

Property

task_id string

The task ID. It is valid for queries for 24 hours.

task_status string

The task status.

Enum 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 transitions during polling:
  • PENDING (Queuing) → RUNNING (Processing) → SUCCEEDED (Success) / FAILED (Failed).
  • The initial query status is usually PENDING (Queuing) or RUNNING (Processing).
  • When the status changes to SUCCEEDED, the response contains the URL of the generated image.
  • If the status is FAILED, check the error message and try again.

submit_time string

The time when the task was submitted. The time zone is UTC+8 and the format is YYYY-MM-DD HH:mm:ss.SSS.

scheduled_time string

The task execution time. The time zone is UTC+8 and the format is YYYY-MM-DD HH:mm:ss.SSS.

end_time string

The task completion time. The time zone is UTC+8 and the format is YYYY-MM-DD HH:mm:ss.SSS.

finished boolean

Whether the task has ended.

  • true: The task has ended.
  • false: The task has not ended.

choices array

The output content generated by the model.

Property

finish_reason string

The reason why the task stopped. The value is stop when the task completes normally.

message object

The message returned by the model.

Property

rolestring

The role of the message, which is fixed to assistant.

contentarray

Property

image string

The URL of the generated image. The image format is PNG.

The URL is valid for 24 hours. Download and save the image in a timely manner.

type string

The type of the output, which is fixed to image.

usage object

Output statistics. Only successful results are counted.

Property

image_count integer

The number of generated images.

size string

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

input_tokens integer

The number of input tokens. Currently fixed at 0.

output_tokens integer

The number of output tokens. Currently fixed at 0.

total_tokensinteger

The total number of tokens. Currently fixed at 0.

request_idstring

The unique request identifier. It can be used for request detail tracing and troubleshooting.

codestring

The error code returned when the request fails. This parameter is not returned when the request succeeds. For details, see Error codes.

messagestring

The detailed error information returned when the request fails. This parameter is not returned when the request succeeds. For details, see Error codes.

Task executed successfully

Task data (such as task status and image URLs) is retained for only 24 hours and is automatically cleared after it expires. Please 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
    }
}

Task execution exception

If the task fails for any reason, the relevant information will be returned, and the code and message fields clearly indicate the cause of the error. See Error codes for troubleshooting.

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

HTTP Asynchronous Call (models at wan2.5 or earlier versions)

ImportantThis API uses the legacy protocol and supports only models at wan2.5 or earlier versions.

Because text-to-image tasks take a long time (usually 1 to 2 minutes), the API uses asynchronous calls. The entire process consists of "Create task -> Poll for results", two core steps, as follows:

The actual time required depends on the number of queued tasks and service execution. Please wait patiently when obtaining the results.

Step 1: Create a task to obtain the task ID

Singapore

POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis

Beijing

POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis

Note

  • After the task is created successfully, use the task_id returned by the API to query the result. The task_id is valid for 24 hours. Do not create duplicate tasks; simply poll for the results.
  • 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 value: Bearer sk-xxxx.

X-DashScope-Asyncstring(required)

The asynchronous processing configuration parameter. HTTP requests support asynchronous calls only, and it must be set toenable.

ImportantIf this request header is missing, the following error is returned: "current user api does not support synchronous calls".

Request Body

model string (Required)

The model name. For text-to-image models, see Models.

Example value: wan2.5-t2i-preview.

NoteFor HTTP calls to wan2.6 models, see HTTP synchronous call and HTTP asynchronous call.

input object (Required)

Basic input information, such as prompts.

Property

prompt string (Required)

The positive prompt, used to describe the elements and visual features you want in the generated image.

Supports both Chinese and English. Each Chinese character, letter, or punctuation mark counts as one character, and the excess is automatically truncated. Length limits vary 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 value: a sitting orange cat with a pleasant expression, lively and cute, realistic and accurate.

For tips on using prompts, see Text-to-image prompt guide.

negative_prompt string (Optional)

The negative prompt, used to describe content you do not want in the image, which constrains the image.

Supports both Chinese and English. The length must not exceed 500 characters, and the excess is automatically truncated.

Example values: low resolution, error, worst quality, low quality, incomplete, extra fingers, bad proportions, etc.

parameters object (Optional)

Image processing parameters, such as setting the image resolution, enabling smart prompt rewriting, and adding a watermark.

Property

size string (Optional)

The resolution of the output image, in the format width*height. Default values and constraints vary by model version:

  • wan2.5-t2i-preview: The default value is 1280*1280. The total pixels are within [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 within [512, 1440], and the maximum resolution is 14401440. For example, 7682700 exceeds the single-side limit and is not supported.

Example value: 1280*1280.

n integer (Optional)

Importantn directly affects the fee. Fee = Unit price × Number of images. Please confirm the Model Price before making a call.

The number of images to generate. The value range is 1~4, and the default is 4. During testing, it is recommended to set this to 1 for low-cost verification.

prompt_extendboolean (Optional)

Whether to enable smart prompt rewriting. When enabled, a large language model rewrites the input prompt intelligently. This significantly improves generation results for short prompts, but increases processing time.

  • true: Default value. Intelligent rewriting is enabled.
  • false: Intelligent rewriting is disabled.

Example value: true.

NoteAfter intelligent rewriting is enabled, the rewritten prompt may introduce copyrighted content, which triggers content moderation and returns the IPInfringementSuspect or DataInspectionFailed error.

If you encounter the preceding errors, set prompt_extend to false and try again. If the prompt itself directly contains the name of a copyrighted character or work, the error persists even after intelligent rewriting is disabled, and you must modify the prompt itself.

watermark boolean (Optional)

Whether to add a watermark. The watermark is located in the lower-right corner of the image, and the text is fixed to “AI-generated”.

  • false: Default value. No watermark is added.
  • true: A watermark is added.

seed integer (Optional)

The random number seed. Value range: [0,2147483647].

Using the same seed parameter value keeps the generated content relatively stable. If this parameter is not specified, the algorithm automatically uses a random number seed.

Note: The model generation process is probabilistic. Even if the same seed is used, the generation results are not guaranteed to be exactly the same each time.

text-to-image

The API Keys differ between the Singapore and Beijing regions. See Obtain and configure API Key

The following is the URL for the Singapore region. The URL varies by region.

When calling, replace {WorkspaceId} with your actual workspace ID.

curl -X POST https://{WorkspaceId}.ap-southeast-1.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
    }
}'

Text-to-image (using a negative prompt)

Use negative_prompt to specify that the generated image should avoid the element "people".

The API Keys differ between the Singapore and Beijing regions. See Obtain and configure API Key

The following is the URL for the Singapore region. The URL varies by region.

When calling, replace {WorkspaceId} with your actual workspace ID.

curl -X POST https://{WorkspaceId}.ap-southeast-1.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.2-t2i-flash",
    "input": {
        "prompt": "雪地,白色小教堂,极光,冬日场景,柔和的光线。",
        "negative_prompt": "人物"
    },
    "parameters": {
        "size": "1024*1024",
        "n": 1
    }
}'

Response parameters

output object

Task output information.

Property

task_id string

The task ID. It is valid for queries for 24 hours.

task_status string

The task status.

Enum 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_idstring

The unique request identifier. It can be used for request detail tracing and troubleshooting.

codestring

The error code returned when the request fails. This parameter is not returned when the request succeeds. For details, see Error codes.

messagestring

The detailed error information returned when the request fails. This parameter is not returned when the request succeeds. For details, see Error codes.

Success response

Save the task_id, which is used to query the task status and results.

{
    "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 for troubleshooting.

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

Step 2: Query the result by task ID

Singapore

GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}

When making calls, replace {WorkspaceId} with your actual Workspace ID.

China (Beijing)

GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}

When making calls, replace {WorkspaceId} with your actual Workspace ID.

Note

  • Polling recommendations: Image generation takes a long time. We recommend that you use a polling mechanism and set an appropriate query interval (for example, 10 seconds) to obtain the results.
  • Status transitions: PENDING (Queuing) → RUNNING (Processing) → SUCCEEDED (Success) / FAILED (Failed).
  • Result URL: After the task succeeds, the image URL is returned and is valid for 24 hours. We recommend that you download the image immediately after you obtain the URL and store it in permanent storage (such as Alibaba Cloud OSS).

Request parameters

Request headers (Headers)

Authorizationstring(Required)

Request authentication. The API uses an Alibaba Cloud Model Studio API Key for authentication. Example value: Bearer sk-xxxx.

URL path parameters (Path parameters)

task_id string(required)

The task ID.

Query task result

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

API Keys differ across regions. Obtain and configure API Key.

If you use models in the China (Beijing) region, replace base_url with https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx, where {WorkspaceId} must be replaced with the actual workspace ID.

curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"

Response parameters

outputobject

Task output information.

Property

task_id string

The task ID. It is valid for queries for 24 hours.

task_status string

The task status.

Enum 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 transitions during polling:
  • PENDING (Queuing) → RUNNING (Processing) → SUCCEEDED (Success) / FAILED (Failed).
  • The initial query status is usually PENDING (Queuing) or RUNNING (Processing).
  • When the status changes to SUCCEEDED, the response contains the URL of the generated image.
  • If the status is FAILED, check the error message and try again.

submit_time string

The time when the task was submitted. The time zone is UTC+8 and the format is YYYY-MM-DD HH:mm:ss.SSS.

scheduled_time string

The task execution time. The time zone is UTC+8 and the format is YYYY-MM-DD HH:mm:ss.SSS.

end_time string

The task completion time. The time zone is UTC+8 and the format is YYYY-MM-DD HH:mm:ss.SSS.

results array of object

The task result list, including image URLs, the prompt, and error messages for partially failed tasks.

Data structure

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

Property

orig_prompt string

The original input prompt, corresponding to the request parameter prompt.

actual_prompt string

After prompt smart rewriting is enabled, the optimized prompt actually used is returned. If this feature is not enabled, this field is not returned.

url string

The image URL. Returned only when task_status is SUCCEEDED. The link is valid for 24 hours, and you can download the image via this URL.

codestring

The error code returned when the request fails. This parameter is not returned when the request succeeds. For details, see Error codes.

messagestring

The detailed error information returned when the request fails. This parameter is not returned when the request succeeds. For details, see Error codes.

task_metrics object

Task result statistics.

Property

TOTAL integer

The total number of tasks.

SUCCEEDED integer

The number of tasks with a successful status.

FAILED integer

The number of tasks with a failed status.

codestring

The error code returned when the request fails. This parameter is not returned when the request succeeds. For details, see Error codes.

messagestring

The detailed error information returned when the request fails. This parameter is not returned when the request succeeds. For details, see Error codes.

usage object

The statistics of the output information. Only successful results are counted.

Property

image_count integer

The number of images the model successfully generated. Billing formula: Fee = Image Count × Unit price.

request_idstring

The unique request identifier. It can be used for request detail tracing and troubleshooting.

Task executed successfully

The image URL is retained for only 24 hours and is automatically cleared after it expires. 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
    }
}

Task execution failed

If a task fails, task_status is set to FAILED, with an error code and message provided. See Error codes for troubleshooting.

{
    "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. As long as one image is generated successfully, the task status will be marked as SUCCEEDED, and the corresponding image URL will be returned. For images that fail to be generated, the corresponding failure reason is returned in the results. In addition, the usage statistics count only successful results. See Error codes for troubleshooting.

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

Task query expired

A task_id can be queried within 24 hours. After that, the query fails and the following error message is returned.

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

Call via DashScope Python SDK

The SDK parameter names are basically the same as those of the HTTP API, and the parameter structure is encapsulated according to language-specific features.

Since text-to-image tasks are time-consuming, the SDK encapsulates the HTTP asynchronous call process at the underlying layer and supports both synchronous and asynchronous call methods.

The actual time required depends on the number of queued tasks and service execution. Please wait patiently when obtaining the results.

wan2.6

Important

  • The following code applies only to the wan2.6 model.
  • Make sure the DashScope Python SDK version is no earlier than 2.0.1 before running the following code. For updates, see Install SDK.

The region and API Key are not interchangeable across regions. The following examples use the Singapore region as an example:

Singapore

https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1

When making calls, replace {WorkspaceId} with your actual Workspace ID.

United States (Virginia)

https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1

China (Beijing)

https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1

When making calls, replace {WorkspaceId} with your actual Workspace ID.

Germany (Frankfurt)

https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1

When making calls, replace {WorkspaceId} with your actual Workspace ID.

The global deployment scope (Frankfurt region) supports asynchronous calls only.

Synchronous call

Request example
import os
import dashscope

# The following is the configuration for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. The region value varies by region.
# If you have not configured the environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"
# The API key is region-specific. To obtain an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
client = dashscope.Client(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

print("----sync call, please wait a moment----")
# generate is a one-step call (submits the task and waits for completion), returning a completed Job
job = client.images.generate(
    model="wan2.6-t2i",
    prompt='一间有着精致窗户的花店,漂亮的木质门,摆放着花朵',
    negative_prompt="",
    prompt_extend=True,
    watermark=False,
    n=1,
    size="1280*1280"
)
print(job)
print(job.image_urls)
Response example

The url is valid for 24 hours. Download the image in a timely manner.

{
    "request_id": "820dd0db-eb42-4e05-8d6a-1ddb4axxxxxx",
    "task_id": "f470bbfd-d955-4165-935b-d35b8eexxxxxx",
    "status": "SUCCEEDED",
    "results": [
        {
            "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx"
        }
    ],
    "usage": {
        "image_count": 1,
        "size": "1280*1280"
    }
}

Asynchronous call

Request example
import os
import dashscope
from dashscope import DashScopeError

# The following is the configuration for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. The region value varies by region.
# 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: https://www.alibabacloud.com/help/model-studio/get-api-key
client = dashscope.Client(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

# Create an asynchronous task
def create_async_task():
    print("Creating async task...")
    job = client.images.jobs.create(
        model="wan2.6-t2i",
        prompt='一间有着精致窗户的花店,漂亮的木质门,摆放着花朵',
        negative_prompt="",
        prompt_extend=True,
        watermark=False,
        n=1,
        size="1280*1280"
    )
    print("Task created successfully:", job)
    return job

# Wait for the task to complete (polling with exponential backoff, 24-hour total budget by default; a FAILED task raises DashScopeError)
def wait_for_completion(task):
    print("Waiting for task completion...")
    done = client.images.jobs.wait(task)
    print("Task succeeded!")
    print("Response:", done)
    print("Image URLs:", done.image_urls)

# Fetch asynchronous task information
def fetch_task_status(task):
    print("Fetching task status...")
    status = client.images.jobs.fetch(task)
    print("Task status:", status.status)

# Cancel the asynchronous task
def cancel_task(task):
    print("Canceling task...")
    response = client.images.jobs.cancel(task)
    print("Task canceled successfully:", response.status)

# Main execution flow
if __name__ == "__main__":
    try:
        task = create_async_task()
        wait_for_completion(task)
    except DashScopeError as e:
        print(f"HTTP返回码:{e.status_code}")
        print(f"错误码:{e.code}")
        print(f"错误信息:{e.message}")
        print("请参考文档:https://www.alibabacloud.com/help/model-studio/error-code")
Response example
  1. Response example for creating a task
{
    "request_id": "c4f11410-ea42-4996-957d-9c82f9xxxxxx",
    "task_id": "f470bbfd-d955-4165-935b-d35b8eexxxxxx",
    "status": "PENDING"
}
  1. Response example for querying node results

The url is valid for 24 hours. Download the image in a timely manner.

{
    "request_id": "7e57e7e8-00b0-4534-9aff-fe31e0xxxxxx",
    "task_id": "f470bbfd-d955-4165-935b-d35b8exxxxxx",
    "status": "SUCCEEDED",
    "results": [
        {
            "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx"
        }
    ],
    "usage": {
        "image_count": 1,
        "size": "1280*1280"
    }
}

Models at wan2.5 and earlier versions

Important

  • The following code applies only to models at wan2.5 and earlier versions.

  • Make sure the DashScope Python SDK version is no lower than 2.0.1 before running the following code.

    For updates, see Install SDK.

The region and API Key are not interchangeable across regions. The following examples use the Singapore region as an example:

Singapore

https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1

When making calls, replace {WorkspaceId} with your actual Workspace ID.

China (Beijing)

https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1

When making calls, replace {WorkspaceId} with your actual Workspace ID.

Synchronous call

Request example
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
import os
import dashscope
from dashscope import DashScopeError

# The following is the configuration for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. The region value varies by region.
# 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: https://www.alibabacloud.com/help/model-studio/get-api-key
client = dashscope.Client(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

print('----sync call, please wait a moment----')
try:
    # generate is a one-step call (submits the task and waits for completion), returning a completed 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)
    # Save the image in the current directory
    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://www.alibabacloud.com/help/model-studio/error-code")
Response example

The url is valid for 24 hours. Download the image in a timely manner.

{
    "request_id": "9d634fda-5fe9-9968-a908-xxxxxx",
    "task_id": "d35658e4-483f-453b-b8dc-xxxxxx",
    "status": "SUCCEEDED",
    "results": [
        {
            "url": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/1.png",
            "orig_prompt": "一间有着精致窗户的花店,漂亮的木质门,摆放着花朵",
            "actual_prompt": "一间精致的花店,窗户上装饰着优雅的雕花,漂亮的木质门上挂着铜制把手。店内摆放着各种色彩鲜艳的花朵,如玫瑰、郁金香和百合等。背景是温馨的室内场景,光线柔和,营造出宁静舒适的氛围。高清写实摄影,近景中心构图。"
        }
    ],
    "task_metrics": {
        "TOTAL": 1,
        "SUCCEEDED": 1,
        "FAILED": 0
    },
    "usage": {
        "image_count": 1
    }
}

Asynchronous call

Request example
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
import os
import dashscope
from dashscope import DashScopeError

# The following is the configuration for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. The region value varies by region.
# 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: https://www.alibabacloud.com/help/model-studio/get-api-key
client = dashscope.Client(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

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():
    job = client.images.jobs.create(
        model="wan2.5-t2i-preview",
        prompt="一间有着精致窗户的花店,漂亮的木质门,摆放着花朵",
        negative_prompt="",
        n=1,
        size='1280*1280',
        prompt_extend=True,
        watermark=False,
        seed=12345
    )
    print(job)
    print(job.task_id, job.status)
    return job

# Wait for the asynchronous task to finish (polling with exponential backoff, 24-hour total budget by default; a FAILED task raises DashScopeError)
def wait_async_task(task):
    done = client.images.jobs.wait(task)
    print(done)
    # save file to current directory
    for url in done.image_urls:
        file_name = PurePosixPath(unquote(urlparse(url).path)).parts[-1]
        with open('./%s' % file_name, 'wb+') as f:
            f.write(requests.get(url).content)

# Fetch asynchronous task information
def fetch_task_status(task):
    status = client.images.jobs.fetch(task)
    print(status)
    print(status.status)

# Cancel the asynchronous task. Only tasks in the PENDING state can be canceled.
def cancel_task(task):
    rsp = client.images.jobs.cancel(task)
    print(rsp)
    print(rsp.status)

if __name__ == '__main__':
    try:
        async_call()
    except DashScopeError as e:
        print(f"HTTP返回码:{e.status_code}")
        print(f"错误码:{e.code}")
        print(f"错误信息:{e.message}")
        print("请参考文档:https://www.alibabacloud.com/help/model-studio/error-code")
Response example
  1. Response example for creating a task
{
	"request_id": "31b04171-011c-96bd-ac00-f0383b669cc7",
	"task_id": "4f90cf14-a34e-4eae-xxxxxxxx",
	"status": "PENDING"
}
  1. Response example for querying node results

The url is valid for 24 hours. Download the image in a timely manner.

{
    "request_id": "9d634fda-5fe9-9968-a908-xxxxxx",
    "task_id": "d35658e4-483f-453b-b8dc-xxxxxx",
    "status": "SUCCEEDED",
    "results": [
        {
            "url": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/xxx.png",
            "orig_prompt": "一间有着精致窗户的花店,漂亮的木质门,摆放着花朵",
            "actual_prompt": "一间精致的花店,窗户上装饰着优雅的雕花,漂亮的木质门上挂着铜制把手。店内摆放着各种色彩鲜艳的花朵,如玫瑰、郁金香和百合等。背景是温馨的室内场景,光线柔和,营造出宁静舒适的氛围。高清写实摄影,近景中心构图。"
        }
    ],
    "task_metrics": {
        "TOTAL": 1,
        "SUCCEEDED": 1,
        "FAILED": 0
    },
    "usage": {
        "image_count": 1
    }
}

Call the DashScope Java SDK

The SDK parameter names are basically the same as those of the HTTP API, and the parameter structure is encapsulated according to language-specific features.

Since text-to-image tasks are time-consuming, the SDK encapsulates the HTTP asynchronous call process at the underlying layer and supports both synchronous and asynchronous call methods.

The actual time required depends on the number of queued tasks and service execution. Please wait patiently when obtaining the results.

wan2.6

Important

  • The following code applies only to the wan2.6-t2i model.
  • Make sure the DashScope Java SDK version is no lower than 2.22.6 before running the following code.

The base_url and API Key are not interchangeable across regions. The following examples use the Singapore region as an example:

Singapore

https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1

When making calls, replace {WorkspaceId} with your actual Workspace ID.

United States (Virginia)

https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1

China (Beijing)

https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1

When making calls, replace {WorkspaceId} with your actual Workspace ID.

Germany (Frankfurt)

https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1

When making calls, replace {WorkspaceId} with your actual Workspace ID.

The global deployment scope (Frankfurt region) supports asynchronous calls only.

Synchronous call

Request example
import com.alibaba.dashscope.aigc.imagegeneration.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.util.Collections;

public class Main {

    static {
        // 以下为新加坡地域URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey="sk-xxx"
    // 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    public static void basicCall() throws ApiException, NoApiKeyException, UploadFileException {
        ImageGenerationMessage message = ImageGenerationMessage.builder()
                .role("user")
                .content(Collections.singletonList(
                        Collections.singletonMap("text", "一间有着精致窗户的花店,漂亮的木质门,摆放着花朵")
                )).build();

        ImageGenerationParam param = ImageGenerationParam.builder()
                .apiKey(apiKey)
                .model("wan2.6-t2i")
                .n(1)
                .size("1280*1280")
                .negativePrompt("")
                .promptExtend(true)
                .watermark(false)
                .messages(Collections.singletonList(message))
                .build();

        ImageGeneration imageGeneration = new ImageGeneration();
        ImageGenerationResult result = null;
        try {
            System.out.println("---sync call, please wait a moment----");
            result = imageGeneration.call(param);
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            throw new RuntimeException(e.getMessage());
        }
        System.out.println(JsonUtils.toJson(result));
    }

    public static void main(String[] args) {
        try {
            basicCall();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
    }
}
Response example

The url is valid for 24 hours. Download the image in a timely manner.

{
    "status_code": 200,
    "request_id": "50b57166-eaaa-4f17-b1e0-35a5ca88672c",
    "code": "",
    "message": "",
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
                            "type": "image"
                        }
                    ]
                }
            }
        ],
        "finished": true
    },
    "usage": {
        "input_tokens": 0,
        "output_tokens": 0,
        "image_count": 1,
        "size": "1280*1280",
        "total_tokens": 0
    }
}

Asynchronous call

Request example
import com.alibaba.dashscope.aigc.imagegeneration.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.util.Collections;

public class Main {

    static {
        // 以下为新加坡地域URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey="sk-xxx"
    // 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    public static void asyncCall() throws ApiException, NoApiKeyException, UploadFileException {
        ImageGenerationMessage message = ImageGenerationMessage.builder()
                .role("user")
                .content(Collections.singletonList(
                        Collections.singletonMap("text", "一间有着精致窗户的花店,漂亮的木质门,摆放着花朵")
                )).build();

        ImageGenerationParam param = ImageGenerationParam.builder()
                .apiKey(apiKey)
                .model("wan2.6-t2i")
                .n(1)
                .size("1280*1280")
                .negativePrompt("")
                .promptExtend(true)
                .watermark(false)
                .messages(Collections.singletonList(message))
                .build();

        ImageGeneration imageGeneration = new ImageGeneration();
        ImageGenerationResult result = null;
        try {
            System.out.println("---async call, creating task----");
            result = imageGeneration.asyncCall(param);
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            throw new RuntimeException(e.getMessage());
        }
        System.out.println(JsonUtils.toJson(result));

        String taskId = result.getOutput().getTaskId();
        // 等待任务完成
        waitTask(taskId);
    }

    public static void waitTask(String taskId) throws ApiException, NoApiKeyException {
        ImageGeneration imageGeneration = new ImageGeneration();
        ImageGenerationResult result = imageGeneration.wait(taskId, apiKey);
        System.out.println(JsonUtils.toJson(result));
    }

    public static void main(String[] args) {
        try {
            asyncCall();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
    }
}
Response example
  1. Response example 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
}
  1. Response example for querying node results

The url is valid for 24 hours. Download the image in a timely manner.

{
    "status_code": 200,
    "request_id": "cbdf1424-306e-4a52-82f3-8bf5d8a99103",
    "code": "",
    "message": "",
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
                            "type": "image"
                        }
                    ]
                }
            }
        ],
        "task_id": "4c861fbe-af89-4a2f-8fc5-4bb15c3139ba",
        "task_status": "SUCCEEDED",
        "submit_time": "2026-01-16 16:36:06.556",
        "scheduled_time": "2026-01-16 16:36:06.591",
        "end_time": "2026-01-16 16:36:25.190",
        "finished": true
    },
    "usage": {
        "input_tokens": 0,
        "output_tokens": 0,
        "size": "1280*1280",
        "total_tokens": 0,
        "image_count": 1
    }
}

Models at wan2.5 and earlier versions

Important

  • The following code applies only to models at wan2.5 and earlier versions.

  • Make sure the DashScope Java SDK version is no lower than 2.22.2 before running the following code.

    If the version is too low, errors such as "url error, please check url!" may occur. Refer to Install SDK to update.

The base_url and API Key are not interchangeable across regions. The following examples use the Singapore region as an example:

Singapore

https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1

When making calls, replace {WorkspaceId} with your actual Workspace ID.

China (Beijing)

https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1

When making calls, replace {WorkspaceId} with your actual Workspace ID.

Synchronous call

Request example
// Copyright (c) Alibaba, Inc. and its affiliates.

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisListResult;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.task.AsyncTaskListParam;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;

import java.util.HashMap;
import java.util.Map;

public class Main {

  static {
     // 以下为新加坡地域URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
     Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
  }

  // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey="sk-xxx"
  // 新加坡和北京地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
  static String apiKey = System.getenv("DASHSCOPE_API_KEY");

  public static void basicCall() throws ApiException, NoApiKeyException {
        // 设置parameters参数
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("prompt_extend", true);
        parameters.put("watermark", false);
        parameters.put("seed", 12345);

        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(apiKey)
                        .model("wan2.5-t2i-preview")
                        .prompt("一间有着精致窗户的花店,漂亮的木质门,摆放着花朵")
                        .n(1)
                        .size("1280*1280")
                        .negativePrompt("")
                        .parameters(parameters)
                        .build();

        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            System.out.println("---sync call, please wait a moment----");
            result = imageSynthesis.call(param);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }
        System.out.println(JsonUtils.toJson(result));
    }

    public static void listTask() throws ApiException, NoApiKeyException {
        ImageSynthesis is = new ImageSynthesis();
        AsyncTaskListParam param = AsyncTaskListParam.builder().build();
        param.setApiKey(apiKey);
        ImageSynthesisListResult result = is.list(param);
        System.out.println(result);
    }

    public static void fetchTask(String taskId) throws ApiException, NoApiKeyException {
        ImageSynthesis is = new ImageSynthesis();
        // If set DASHSCOPE_API_KEY environment variable, apiKey can null.
        ImageSynthesisResult result = is.fetch(taskId, apiKey);
        System.out.println(result.getOutput());
        System.out.println(result.getUsage());
    }

    public static void main(String[] args){
        try{
            basicCall();
            //listTask();
        }catch(ApiException|NoApiKeyException e){
            System.out.println(e.getMessage());
        }
    }
}
Response example

The url is valid for 24 hours. Download the image in a timely manner.

{
    "request_id": "22f9c744-206c-9a78-899a-xxxxxx",
    "output": {
        "task_id": "4a0f8fc6-03fb-4c44-a13a-xxxxxx",
        "task_status": "SUCCEEDED",
        "results": [{
           "orig_prompt": "一间有着精致窗户的花店,漂亮的木质门,摆放着花朵",
            "actual_prompt": "一间有着精致雕花窗户的花店,漂亮的深色木质门微微敞开。店内摆放着各式各样的鲜花,包括玫瑰、百合和向日葵,色彩鲜艳,香气扑鼻。背景是温馨的室内场景,光线柔和,透过窗户洒在花朵上。高清写实摄影,中景构图。",
            "url": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/1.png"
        }],
        "task_metrics": {
            "TOTAL": 1,
            "SUCCEEDED": 1,
            "FAILED": 0
        }
    },
    "usage": {
        "image_count": 1
    }
}

Asynchronous call

Request example
// Copyright (c) Alibaba, Inc. and its affiliates.

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;

import java.util.HashMap;
import java.util.Map;

public class Main {
    static {
        // 以下为新加坡地域URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey="sk-xxx"
    // 新加坡和北京地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/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);
    }

    /**
     * 创建异步任务
     * @return taskId
     */
    public String createAsyncTask() {
        // 设置parameters参数
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("prompt_extend", true);
        parameters.put("watermark", false);
        parameters.put("seed", 12345);

        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(apiKey)
                        .model("wan2.5-t2i-preview")
                        .prompt("一间有着精致窗户的花店,漂亮的木质门,摆放着花朵")
                        .n(1)
                        .size("1280*1280)
                        .negativePrompt("")
                        .parameters(parameters)
                        .build();

        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            result = imageSynthesis.asyncCall(param);
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
        System.out.println(JsonUtils.toJson(result));
        String taskId = result.getOutput().getTaskId();
        System.out.println("taskId=" + taskId);
        return taskId;
    }

    /**
     * 等待异步任务结束
     * @param taskId 任务id
     * */
    public void waitAsyncTask(String taskId) {
        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            //环境变量配置后,可在这里将apiKey设置为null
            result = imageSynthesis.wait(taskId, apiKey);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }
        System.out.println(JsonUtils.toJson(result));
        System.out.println(JsonUtils.toJson(result.getOutput()));
    }

    public static void main(String[] args){
        Main main = new Main();
        main.asyncCall();
    }

}
Response example
  1. Response example for creating a task
{
	"request_id": "5dbf9dc5-4f4c-9605-85ea-542f97709ba8",
	"output": {
		"task_id": "7277e20e-aa01-4709-xxxxxxxx",
		"task_status": "PENDING"
	}
}
  1. Response example for querying node results
{
    "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
    }
}

Limits

  • Data validity: The task task_id and image url are retained for only 24 hours, after which they can no longer be queried or downloaded.
  • Content moderation: Both the input prompt and the output images go through content safety review. Requests containing non-compliant content will return the "IPInfringementSuspect" or "DataInspectionFailed" error. For more information, see Error codes.

Billing and rate limits

  • For the model free quota and billing unit prices, see the Model Studio console.
  • For model rate limits, see Wan.
  • Billing details: You are billed based on the number of images successfully generated. Failed model calls or processing errors do not incur any fees and do not consume the new-user free quota.

Error codes

If a model call fails and returns an error message, see Error codes for troubleshooting.