Wan -image-to-video-first and last frames API reference(2.2)
The Wan 2.2 model generates a smoothly transitioning video from a first frame , a last frame, and a text prompt .
Related documents: User guide
Usage notes
To ensure successful API calls, your model, endpoint URL, and API key must be in the same region. Cross-region calls will fail.
- Select a model: Confirm the region where the model is available.
- Select a URL: Choose the endpoint URL that corresponds to your region. Both HTTP URLs and DashScope SDK URLs are supported.
- Configure your API key: Select a region, get your API key, and then set it as an environment variable.
- Install the SDK: To make API calls using the SDK, install the DashScope SDK.
NoteThe code examples in this topic apply to China (Beijing).
ImportantAlibaba Cloud Model Studio has released workspace-specific domains for the China (Beijing) and Singapore regions. The new dedicated domains deliver superior performance and higher stability for inference requests. We recommend migrating to the new domains:
- China (Beijing): from
https://dashscope.aliyuncs.comtohttps://{WorkspaceId}.cn-beijing.maas.aliyuncs.com - Singapore: from
https://dashscope-intl.aliyuncs.comtohttps://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com
{WorkspaceId} is your workspace ID, which can be found on the Workspace Details page in the Alibaba Cloud Model Studio console. The existing domain remains fully functional.
HTTP call
Because image-to-video tasks are long-running operations that typically take 1 to 5 minutes, the API uses an asynchronous call. The process involves two core steps: create a task, then poll for the result.
Step 1: Create a task to obtain the task ID
China (Beijing)
POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/image2video/video-synthesis
Replace {WorkspaceId} with your actual workspace ID.
Singapore
POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image2video/video-synthesis
Replace {WorkspaceId} with your actual workspace ID.
Note
- After the task is created successfully, use the
task_idreturned by the API to query the result. The task_id is valid for 24 hours. Do not create duplicate tasks; simply use polling to obtain the result.
Request parametersRequest headersContent-Type The content type of the request. Must be Authorization Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx. X-DashScope-Async Enables asynchronous processing. HTTP requests support only asynchronous calls. Must be set to ImportantIf this request header is missing, the error "current user api does not support synchronous calls" is returned. Request bodymodel The name of the model. Example: wan2.2-kf2v-flash. For details, see the Model Studio console. input Contains the primary input for the task, such as the prompt. parameters Video processing parameters. | First and last framesGenerates a video based on a first frame, a last frame, and a prompt. Base64 encodingThe first_frame_url and last_frame_url parameters support Base64-encoded image strings. Download the first_frame_base64 and last_frame_base64 files and paste their full content into the corresponding parameters. For format details, see How to input images. Video effectsYou must provide the Different models support different effect templates. To avoid call failures, refer to the Wan image-to-video effect list before making a call. Negative promptUse the negative_prompt parameter to exclude certain elements, such as people, from the generated video. |
Response parametersoutput The output information for the task. request_id Unique request identifier for tracing and troubleshooting. code Error code. Returned only for failed requests. See Error codes. message Detailed error message. Returned only for failed requests. See Error codes. | Successful responsePlease save the task_id, which is used to query the task status and results. Error responseTask creation failed. See Error codes. |
Step 2: Query the result by task ID
China (Beijing)
GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}
Replace {WorkspaceId} with your actual workspace ID.
Singapore
GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}
Replace {WorkspaceId} with your actual workspace ID.
Note
- Polling recommendation: Video generation takes several minutes. It is recommended to adopt a polling mechanism and set a reasonable query interval (for example, 15 seconds) to obtain the result.
- Task status transitions: PENDING (Queuing) → RUNNING (Processing) → SUCCEEDED (Success) / FAILED (Failed).
- Result link: When the task succeeds, a video link is returned, valid for 24 hours. We recommend downloading it immediately after obtaining the link and transferring it to permanent storage (such as Alibaba Cloud OSS).
- task_id validity: 24 hours. After it expires, the result can no longer be queried, and the API will return the task status as
UNKNOWN. - RPS limit: The default RPS of the query API is 20. For higher-frequency queries or event notifications, we recommend configuring asynchronous task callbacks.
- More operations: For batch queries, task cancellation, and other operations, see Manage asynchronous tasks.
Request parametersRequest headersAuthorization Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx. Path parameterstask_id The ID of the task. | Query task resultPlease replace
|
Response parametersoutput The output information for the task. usage Task usage statistics. Only successful results are counted. request_id Unique request identifier for tracing and troubleshooting. | Task succeededVideo URLs are valid for only 24 hours and then automatically purged. Save generated videos promptly. Task failedIf the task execution fails, task_status will be set to FAILED, and an error code and message will be provided. See Error codes for troubleshooting. Task query expiredThe task_id can be used for queries for 24 hours. After it expires, the query will no longer be available, and the following error message will be returned. |
DashScope SDK calls
The SDK's parameter names are largely consistent with the HTTP API, and the parameter structure follows the conventions of each programming language.
Because image-to-video tasks are long-running (typically 1–5 minutes), the SDK handles the asynchronous HTTP calls internally, supporting both synchronous and asynchronous call methods.
The actual processing time depends on the number of tasks in the queue and service performance. Please be patient.
Python SDK calls
ImportantBefore you run the following code, ensure your DashScope Python SDK version is at least2.0.1.
Older versions may trigger errors such as "url error, please check url!". See Install SDK to update.
Set the region based on the model's region (passed in when constructing the Client; the region value varies by region):
China (Beijing)
region="cn-beijing"
Replace {WorkspaceId} with your actual workspace ID.
Singapore
region="ap-southeast-1"
Replace {WorkspaceId} with your actual workspace ID.
Sample code
Synchronous call
This example demonstrates three image input methods: public URL, Base64 encoding, and local file path.
Request example
import base64
import os
import mimetypes
import dashscope
from dashscope import DashScopeError
# 以下为华北2(北京)地域的配置。请将 {WorkspaceId} 替换为您的百炼业务空间ID,各地域的region取值不同。
client = dashscope.Client(
# 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
# 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="cn-beijing",
)
# --- 辅助函数:用于 Base64 编码 ---
# 格式为 data:{MIME_type};base64,{base64_data}
def encode_file(file_path):
mime_type, _ = mimetypes.guess_type(file_path)
if not mime_type or not mime_type.startswith("image/"):
raise ValueError("不支持或无法识别的图像格式")
with open(file_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
return f"data:{mime_type};base64,{encoded_string}"
"""
图像输入方式说明:
以下提供了三种图片输入方式,三选一即可
1. 使用公网URL - 适合已有公开可访问的图片
2. 使用本地文件 - 适合本地开发测试
3. 使用Base64编码 - 适合私有图片或需要加密传输的场景
"""
# 【方式一】使用公网图片 URL
first_frame_url = "https://wanx.alicdn.com/material/20250318/first_frame.png"
last_frame_url = "https://wanx.alicdn.com/material/20250318/last_frame.png"
# 【方式二】使用本地文件(支持绝对路径和相对路径)
# 格式要求:file:// + 文件路径
# 示例(绝对路径):
# first_frame_url = "file://" + "/path/to/your/first_frame.png" # Linux/macOS
# last_frame_url = "file://" + "C:/path/to/your/last_frame.png" # Windows
# 示例(相对路径):
# first_frame_url = "file://" + "./first_frame.png" # 以实际路径为准
# last_frame_url = "file://" + "./last_frame.png" # 以实际路径为准
# 【方式三】使用Base64编码的图片
# first_frame_url = encode_file("./first_frame.png") # 以实际路径为准
# last_frame_url = encode_file("./last_frame.png") # 以实际路径为准
def sample_sync_call_kf2v():
print('please wait...')
# generate 为一步式调用(提交任务并等待完成),返回已完成的 Job
# first_frame_url / last_frame_url 为 input 段字段,不在具名签名内,经 extra_input 透传
try:
job = client.videos.generate(model="wan2.2-kf2v-flash",
prompt="写实风格,一只黑色小猫好奇地看向天空,镜头从平视逐渐上升,最后俯拍它的好奇的眼神。",
extra_input={'first_frame_url': first_frame_url,
'last_frame_url': last_frame_url},
resolution="720P",
prompt_extend=True)
print(job)
print(job.video_url)
except DashScopeError as e:
print(f"HTTP返回码:{e.status_code}")
print(f"错误码:{e.code}")
print(f"错误信息:{e.message}")
print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")
if __name__ == '__main__':
sample_sync_call_kf2v()
Response example
The video_url is valid for 24 hours. Please download the video promptly.
{
"request_id": "efa545b3-f95c-9e3a-a3b6-xxxxxx",
"task_id": "721164c6-8619-4a35-a6d9-xxxxxx",
"status": "SUCCEEDED",
"video_url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.mp4?xxxxx",
"task_metrics": {
"TOTAL": 1,
"SUCCEEDED": 1,
"FAILED": 0
},
"usage": {
"video_count": 1,
"video_duration": 5,
"video_ratio": "standard"
}
}
Asynchronous call
This example demonstrates an asynchronous call, which returns the task ID immediately; use fetch to check the task status, or call wait to block until the task completes (with automatic polling).
Request example
import os
import dashscope
from dashscope import DashScopeError
# 以下为华北2(北京)地域的配置,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的region取值不同。
client = dashscope.Client(
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="cn-beijing",
)
Java SDK calls
ImportantBefore you run the following code, ensure your DashScope Java SDK version is at least2.20.9.
Older versions may trigger errors such as "url error, please check url!". See Install SDK to update.
Sample code
Synchronous call
This example demonstrates a synchronous call and supports three image input methods: public URL, Base64 encoding, and local file path.
Request example
// Copyright (c) Alibaba, Inc. and its affiliates.
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesis;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisParam;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
/**
* 环境要求
* dashscope java SDK >= 2.20.9
* 更新maven依赖:
* https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
*/
public class Kf2vSync {
static {
// 以下为华北2(北京)地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
Asynchronous call
This example demonstrates an asynchronous call, which immediately returns a task ID. You must then poll for the task status or wait for the task to complete.
Request example
// Copyright (c) Alibaba, Inc. and its affiliates.
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesis;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisListResult;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisParam;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.task.AsyncTaskListParam;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;
import java.util.HashMap;
import java.util.Map;
/**
* 环境要求
* dashscope java SDK >= 2.20.9
* 更新maven依赖:
* https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
*/
public class Kf2vAsync {
static {
// 以下为华北2(北京)地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
Limitations
- Data retention: The task
task_idand videovideo_urlare retained for 24 hours, after which they cannot be queried or downloaded. - Audio support: The service generates silent videos only. To generate audio, use speech synthesis.
- Content Moderation: Content Moderation reviews all input prompts, images, and output videos. If any content violates the usage policies, the service returns an "IPInfringementSuspect" or "DataInspectionFailed" error. For details, see Error codes.
Error codes
If a model call fails, see Error codes for troubleshooting.
FAQ
Q: How to generate a specific aspect ratio?
A: The output video's aspect ratio depends on the first frame image (first_frame_url). However, an exact ratio (such as a strict 3:4) cannot be guaranteed, and may deviate slightly.
-
Why does the aspect ratio deviate?
The model uses the aspect ratio of the input image as the baseline and, combined with the total pixels of the configured resolution tier (resolution), automatically calculates the closest valid resolution. Because the video's length and width must be multiples of 16, the model makes minor adjustments to the final resolution. Therefore, the output ratio cannot be guaranteed to be exactly 3:4, but it will be very close.
- For example: with an input image of 750×1000 (aspect ratio 3:4 = 0.75) and resolution set to "720P" (target total pixels approximately 920,000), the actual output is 816×1104 (aspect ratio ≈ 0.739, total pixels approximately 900,000).
-
Best practices:
- Input Image: For best results, use a first frame image that matches your target aspect ratio.
- Post-processing: If a strict aspect ratio is required, use a video editing tool to crop the generated video or add black bars.
Q: How do I get the domain name whitelist for video storage?
A: Videos generated by models are stored in OSS. The API returns a temporary public URL. To configure a firewall whitelist for this download URL, note the following: The underlying storage may change dynamically based on business conditions. This topic does not provide a fixed OSS domain name whitelist to prevent access issues caused by outdated information. If you have security control requirements, contact your account manager to obtain the latest OSS domain name list.