All Products
Search
Document Center

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

Last Updated:Nov 14, 2025

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

Quick links: Try Wan online

Note

The features on the official Wan website may differ from the capabilities supported by the API. This document describes the API's capabilities and is updated promptly when new features are released.

Overview

Model

Description

Output image format

wan2.5-t2i-preview Recommended

Wan 2.5 Preview

Removes the single-side length limit. You can freely select dimensions within the total pixel area and aspect ratio constraints.

For example, it supports 768*2700. In contrast, versions 2.2 and earlier have a single-side limit of 1400 pixels.

Image resolution: Total pixels between 768*768 and 1440*1440.

Image aspect ratio: [1:4, 4:1]
Image format: png

wan2.2-t2i-flash Recommended

Wan 2.2 Flash Edition

50% faster than the 2.1 model.

Image resolution: Width and height are both between 512 and 1440 pixels.

Image format: png

wan2.2-t2i-plus Recommended

Wan 2.2 Professional Edition

Improved stability and success rate compared to the 2.1 model.

wanx2.1-t2i-turbo

Wan 2.1 Turbo Edition

wanx2.1-t2i-plus

Wan 2.1 Professional Edition

wanx2.0-t2i-turbo

Wan 2.0 Turbo Edition

Note

Before you make a call, see Models for the models supported in each region.

Prerequisites

Before making a call, obtain an API key and set the API key as an environment variable. To make calls using the SDK, install the DashScope SDK.

Important

The Beijing and Singapore regions have separate API keys and request endpoints. Do not use them interchangeably. Cross-region calls cause authentication failures or service errors.

HTTP

Text-to-image tasks take a long time to process, typically 1 to 2 minutes. Therefore, the API uses asynchronous calls. The process involves two core steps: Create a task -> Poll for the result.

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

Step 1: Create a task and get the 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. Use polling to retrieve the result.

Request parameters

Text-to-image

The API keys for the Singapore and Beijing regions are different. Obtain and configure an API key
The provided URL is for the Singapore region. For models in the Beijing region, use the following URL: 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": "1024*1024",
        "n": 1
    }
}'    

Text-to-image (with a negative prompt)

Use `negative_prompt` to prevent "people" from appearing in the generated image.

The API keys for the Singapore and Beijing regions are different. Obtain an API key
The default URL is for the Singapore region. For models in the Beijing region, use the following URL instead: 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": "people"
    },
    "parameters": {
        "size": "1024*1024",
        "n": 1
    }
}'
Request headers

Content-Type string (Required)

The content type of the request. Set this parameter to application/json.

Authorization string (Required)

The identity authentication credentials for the request. This API uses an Model Studio API key for identity authentication. Example: Bearer sk-xxxx.

X-DashScope-Async string (Required)

The asynchronous processing configuration parameter. HTTP requests support only asynchronous processing. You must set this parameter to enable.

Important

If this request header is missing, the error message "current user api does not support synchronous calls" is returned.

Request body

model string (Required)

The model name. Example: `wan2.5-t2i-preview`.

For more information about each model, see Models and pricing.

input object (Required)

Basic input information, such as the prompt.

Properties

prompt string (Required)

The positive prompt. It describes the elements and visual features you want in the generated image.

Both Chinese and English are supported. Each Chinese character or letter counts as one character. Text that exceeds the limit is automatically truncated. The length limit varies by model version:

  • wan2.5-t2i-preview: Up to 2000 characters.

  • Models of version 2.2 and earlier: Up to 800 characters.

Example: A sitting orange cat, happy 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. It describes the content you do not want in the image and can be used to constrain the image content.

Both Chinese and English are supported. The length is limited to 500 characters. Text that exceeds the limit is automatically truncated.

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

parameters object (Optional)

Image editing parameters. Use these to set the image resolution, enable prompt rewriting, add watermarks, and more.

Properties

size string (Optional)

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

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

  • Models of version 2.2 and earlier: The default is 1024*1024. The width and height must be between 512 and 1440 pixels, with a maximum resolution of 1440*1440. For example, 768*2700 is not supported because it exceeds the maximum value for a single dimension.

Example: `1280*1280`.

Recommended resolutions for common aspect ratios

  • 1:1: 1280*1280 or 1024*1024

  • 2:3: 800*1200

  • 3:2: 1200*800

  • 3:4: 960*1280

  • 4:3: 1280*960

  • 9:16: 720*1280

  • 16:9: 1280*720

  • 21:9: 1344*576

n integer (Optional)

Important

The value of n directly affects the cost. Cost = Unit Price * Number of Images. Before making a call, review the model pricing.

The number of images to generate. The value must be an integer from 1 to 4. The default is 4. We recommend setting this to 1 during testing to verify results at a low cost.

prompt_extend boolean (Optional)

Specifies whether to enable prompt rewriting. If enabled, a large language model rewrites the input prompt. This can significantly improve results for short prompts but increases the processing time.

  • true

  • false

The default value for this parameter varies by model version:

  • wan2.5-t2i-preview: The default is false.

  • wan2.2 and earlier: The default is true.

Example: true.

watermark boolean (Optional)

Specifies whether to add a watermark. The watermark is placed in the lower-right corner of the image, saying "AI Generated".

  • false (default)

  • true

seed integer (Optional)

The random number seed. The value must be an integer from [0, 2147483647].

If you do not provide a seed, the algorithm automatically generates one. If you provide a seed, the algorithm generates a seed for each of the n images. For example, if `n` is 4, the seeds will be seed, seed+1, seed+2, and seed+3.

To improve the reproducibility of the results, use a fixed seed value.

Note that because of the probabilistic nature of the model, using the same seed does not guarantee identical results every time.

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

The task creation failed. For more information, see Error messages to resolve the issue.

{
    "code":"InvalidApiKey",
    "message":"Invalid API-key provided.",
    "request_id":"fb53c4ec-1c12-4fc4-a580-xxxxxx"
}

output object

Task output information.

Properties

task_id string

The task ID. The query is valid for 24 hours.

task_status string

The task status.

Enumeration

  • PENDING

  • RUNNING

  • SUCCEEDED

  • FAILED

  • CANCELED

  • UNKNOWN

request_id string

The unique request ID. You can use this ID to trace and troubleshoot issues.

code string

The error code for a failed request. This parameter is not returned if the request is successful. For more information, see Error messages.

message string

The detailed information about a failed request. This parameter is not returned if the request is successful. For more information, see Error messages.

Step 2: Query the result by task ID

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

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

Note
  • Polling suggestion: Image generation takes several minutes. Use a polling mechanism and set a reasonable query interval, such as 10 seconds, to retrieve the result.

  • Task status transition: PENDING (In queue) → RUNNING (Processing) → SUCCEEDED (Successful) or FAILED (Failed).

  • Result link: After the task is successful, an image link is returned. The link is valid for 24 hours. After you retrieve the link, immediately download and save the image to a permanent storage service, such as Alibaba Cloud OSS.

Request parameters

Query task result

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

The API keys for the Singapore and Beijing regions are different. Obtain an API key.
The following code provides the base_url for the Singapore region. If you use a model in the Beijing region, replace the base_url with https://dashscope.aliyuncs.com/api/v1/tasks/{task_id}
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 identity authentication credentials for the request. This API uses an Model Studio API key for identity authentication. Example: Bearer sk-xxxx.

URL path parameters

task_id string (Required)

The task ID.

Response parameters

Task successful

Image URLs are retained for only 24 hours and are automatically purged after this period. You must save the 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. A variety of fresh flowers, including roses, lilies, and sunflowers, are displayed in vibrant colors. 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

If a task fails, task_status is set to FAILED, and an error code and message are provided. For more information, see Error messages 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
        }
    }
}

Task partially failed

The model can generate multiple images in a single task. If at least one image is generated successfully, the task status is marked as SUCCEEDED, and the corresponding image URL is returned. For images that fail to generate, the result contains the reason for the failure. In addition, only successful results are counted in usage statistics. For more information, see Error messages to resolve the issue.

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

The task_id is valid for 24 hours. After this period, 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"
    }
}

output object

Task output information.

Properties

task_id string

The task ID. The query is valid for 24 hours.

task_status string

The task status.

Enumeration

  • PENDING

  • RUNNING

  • SUCCEEDED

  • FAILED

  • CANCELED

  • UNKNOWN

Status transitions during polling:

  • PENDING (In queue) → RUNNING (Processing) → SUCCEEDED (Successful) or FAILED (Failed).

  • The status of the first query is usually PENDING (In queue) or RUNNING (Processing).

  • If the status changes to SUCCEEDED, the response contains the generated image URL.

  • If the status is FAILED, check the error message and retry.

submit_time string

The time when the task was submitted. The format is YYYY-MM-DD HH:mm:ss.SSS.

scheduled_time string

The time when the task started running. The format is YYYY-MM-DD HH:mm:ss.SSS.

end_time string

The time when the task was completed. The format is YYYY-MM-DD HH:mm:ss.SSS.

results array of object

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

Data structure

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

Properties

orig_prompt string

The original input prompt. This corresponds to the prompt request parameter.

actual_prompt string

If prompt rewriting is enabled, this parameter returns the actual optimized prompt that is used. If this feature is disabled, this parameter is not returned.

url string

The URL of the image. This is returned only when `task_status` is `SUCCEEDED`. The link is valid for 24 hours. You can download the image from this URL.

code string

The error code for a failed request. This parameter is not returned if the request is successful. For more information, see Error messages.

message string

The detailed information about a failed request. This parameter is not returned if the request is successful. For more information, see Error messages.

task_metrics object

The task result statistics.

Properties

TOTAL integer

The total number of tasks.

SUCCEEDED integer

The number of successful tasks.

FAILED integer

The number of failed tasks.

code string

The error code for a failed request. This parameter is not returned if the request is successful. For more information, see Error messages.

message string

The detailed information about a failed request. This parameter is not returned if the request is successful. For more information, see Error messages.

usage object

Statistics for the output. Only successful results are counted.

Properties

image_count integer

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

request_id string

The unique request ID. You can use this ID to trace and troubleshoot issues.

DashScope SDK

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

Because text-to-image tasks take a long time (typically 1 to 2 minutes), the SDK encapsulates the HTTP asynchronous call process and supports both synchronous and asynchronous call methods.

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

Python SDK

Note

Install the latest version of the DashScope Python SDK. Otherwise, a runtime error may occur. For more information, see Install or upgrade the SDK.

Synchronous

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 URL is 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. Get an API key: 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='1024*1024',
                          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. 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 elegantly carved windows and a beautiful wooden door with a brass handle. A variety of colorful flowers, such as roses, tulips, and lilies, are on display. The background is a warm indoor scene with soft light, creating a peaceful and comfortable atmosphere. High-definition realistic photography, close-up center composition."
        }],
        "submit_time": "2025-01-08 19:36:01.521",
        "scheduled_time": "2025-01-08 19:36:01.542",
        "end_time": "2025-01-08 19:36:13.270",
        "task_metrics": {
            "TOTAL": 1,
            "SUCCEEDED": 1,
            "FAILED": 0
        }
    },
    "usage": {
        "image_count": 1
    }
}

Asynchronous

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 URL is 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. Get an API key: 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='1024*1024',
                                    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 information about the asynchronous task
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. Response example for creating a task

{
	"status_code": 200,
	"request_id": "31b04171-011c-96bd-ac00-f0383b669cc7",
	"code": "",
	"message": "",
	"output": {
		"task_id": "4f90cf14-a34e-4eae-xxxxxxxx",
		"task_status": "PENDING",
		"results": []
	},
	"usage": null
}

2. Response example for querying a task result

The URL is valid for 24 hours. 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 elegantly carved windows and a beautiful wooden door with a brass handle. A variety of colorful flowers, such as roses, tulips, and lilies, are on display. The background is a warm indoor scene with soft light, creating a peaceful and comfortable atmosphere. High-definition realistic photography, close-up center composition."
        }],
        "submit_time": "2025-01-08 19:36:01.521",
        "scheduled_time": "2025-01-08 19:36:01.542",
        "end_time": "2025-01-08 19:36:13.270",
        "task_metrics": {
            "TOTAL": 1,
            "SUCCEEDED": 1,
            "FAILED": 0
        }
    },
    "usage": {
        "image_count": 1
    }
}

Java SDK

Note

Install the latest version of the DashScope Java SDK. Otherwise, a runtime error may occur. For more information, see Install or upgrade the SDK.

Synchronous

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 URL is 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. Get an API key: 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 the parameters
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("prompt_extend", true);
        parameters.put("watermark", false);
        parameters.put("seed", 12345);

        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(apiKey)
                        .model("wan2.5-t2i-preview")
                        .prompt("A flower shop with exquisite windows, a beautiful wooden door, and flowers on display")
                        .n(1)
                        .size("1024*1024")
                        .negativePrompt("")
                        .parameters(parameters)
                        .build();

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

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

    public static void fetchTask(String taskId) throws ApiException, NoApiKeyException {
        ImageSynthesis is = new ImageSynthesis();
        // If the DASHSCOPE_API_KEY environment variable is set, apiKey can be 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 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 that is slightly ajar. A variety of fresh flowers, including roses, lilies, and sunflowers, are displayed in vibrant colors and are fragrant. 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

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 URL is 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. Get an API key: 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 the parameters
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("prompt_extend", true);
        parameters.put("watermark", false);
        parameters.put("seed", 12345);

        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(apiKey)
                        .model("wan2.5-t2i-preview")
                        .prompt("A flower shop with exquisite windows, a beautiful wooden door, and flowers on display")
                        .n(1)
                        .size("1024*1024")
                        .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 {
            // If you have configured 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. Response example for creating a task

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

2. Response example 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 that is slightly ajar. A variety of fresh flowers, including roses, lilies, and sunflowers, are displayed in vibrant colors and are fragrant. 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
    }
}

Limits

  • 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 the output image are both subject to content moderation. Requests with non-compliant content result in an "IPInfringementSuspect" or "DataInspectionFailed" error. For more information, see Error messages.

  • Network access configuration: Image links are stored in Alibaba Cloud OSS. If your business system cannot access external OSS links because of security policies, add the following OSS domain names to your network access whitelist.

    # OSS domain name list
    dashscope-result-bj.oss-cn-beijing.aliyuncs.com
    dashscope-result-hz.oss-cn-hangzhou.aliyuncs.com
    dashscope-result-sh.oss-cn-shanghai.aliyuncs.com
    dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com
    dashscope-result-zjk.oss-cn-zhangjiakou.aliyuncs.com
    dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com
    dashscope-result-hy.oss-cn-heyuan.aliyuncs.com
    dashscope-result-cd.oss-cn-chengdu.aliyuncs.com
    dashscope-result-gz.oss-cn-guangzhou.aliyuncs.com
    dashscope-result-wlcb-acdr-1.oss-cn-wulanchabu-acdr-1.aliyuncs.com

Billing and rate limiting

  • For information about the free quota and unit price of the model, see Models.

  • For more information about model rate limiting, see Wan.

  • Billing description:

    • Billing is based on the number of successfully generated images. You are charged only when the query result API returns a task_status of SUCCEEDED and an image is successfully generated.

    • Failed model calls or processing errors do not incur any fees and do not consume your free quota.

Error codes

If a call fails, see Error messages for troubleshooting.

FAQ

Q: How do I view the number of model calls?

A: One hour after the model call is complete, you can go to the Model Observation (Singapore) or Model Observation (Beijing) page to view metrics such as the number of calls and success rate. For more information, see How do I view model call records?