Skip to main content

Wan-First-and-Last-Frame Video Generation API Reference (2.2)

The Wan2.2 first-and-last-frame video generation model generates a video with smooth transitions based on the first frame image, last frame image, and text prompt.

Related documents: User Guide

Scope

To ensure successful calls, make sure the model, Endpoint URL, and API Key belong to the same region. Cross-region calls will fail.
The sample code in this document applies to the Singapore region.
Alibaba Cloud Model Studio has launched workspace-specific domains for the China (Beijing) and Singapore regions, which deliver superior performance and higher stability for inference requests. We recommend migrating to the new domains:
  • China (Beijing) region: migrate from https://dashscope.aliyuncs.com to https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com
  • Singapore region: migrate from https://dashscope-intl.aliyuncs.com to https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com
Here, {WorkspaceId} is your workspace ID, which you can view on the Workspace Details page in the Alibaba Cloud Model Studio console. The existing domains still work as usual.

HTTP Calls

Since image-to-video tasks take a long time to complete (usually 1 to 5 minutes), the API uses asynchronous calls. The entire process consists of two core steps, "Create Task -> Poll for Result", as follows:

Step 1: Create a task to obtain the task ID

  • Singapore
  • Beijing
POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image2video/video-synthesisWhen making calls, replace {WorkspaceId} with your actual workspace ID.
  • After the task is created, use the task_id returned by the API to query the result. The task_id is valid for 24 hours. Do not create the same task repeatedly; just poll for the result.
  • For a beginner's guide, see Postman.

Request Parameters

Request Headers
Content-Typestring(Required)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)Asynchronous processing configuration parameter. HTTP requests support asynchronous mode only and must be set to enable.
If 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.2-kf2v-flash.For details, see the Bailian console.input object (Required)Basic input information, such as prompts.

Property

prompt string (Optional)Text prompt. Supports Chinese and English, with a length of no more than 800 characters, where each Chinese character/letter counts as one character; any excess is automatically truncated.If the subject and scene differ significantly between the first and last frames, it is recommended to describe the change process, such as camera movement (the camera moves to the left) or subject motion (a person runs forward).Example value: A black kitten looks up at the sky curiously, the camera gradually rises from eye level, and finally shoots from above to capture its curious gaze.For tips on using prompts, see the T2V/I2V Prompt Guide.negative_prompt string (Optional)Negative prompt, used to describe content you do not want to see in the video, which can constrain the video visuals.Supports Chinese and English, with a length of no more than 500 characters; any excess is automatically truncated.Example value: low resolution, fault, worst quality, low quality, incomplete, extra fingers, bad proportions, etc.first_frame_url string (Required)First Frame Image URL. The aspect ratio of the output video is consistent with that of the first frame image.The URL must be a publicly accessible address, supporting the HTTP or HTTPS protocol.Image limits:
  • Image format: JPEG, JPG, PNG (transparent channels are not supported), BMP, WEBP.
  • Image resolution: The image width and height range is [240,8000], in pixels.
  • File size: No more than 10MB.
last_frame_url string (Required)Last frame image URL.The URL must be a publicly accessible address, supporting the HTTP or HTTPS protocol.Image limits:
  • Image format: JPEG, JPG, PNG (transparent channels are not supported), BMP, WEBP.
  • Image resolution: The image width and height range is [240,8000], in pixels. The last frame image resolution can differ from the first frame and does not need to be forcibly aligned.
  • File size: No more than 10MB.
parameters object (Optional)Video processing parameters.

Property

resolution string (Optional)
resolution directly affects the fee. For the same model: 1080P > 720P > 480P. Please confirm on the Bailian console before making a call.
The resolution tier of the generated video. It only adjusts the video clarity (total pixels) and does not change the video aspect ratio. The video aspect ratio will be consistent with that of the first frame image first_frame_url.The default value and available enumeration values of this parameter depend on the model parameter. The rules are as follows:
  • wan2.2-kf2v-flash: Valid values: 480P, 720P, 1080P. Default value: 720P.
  • wan2.1-kf2v-plus: Valid value: 720P. Default value: 720P.
Example value: 720P.duration integer (optional)
duration directly affects the fee. Billing is based on seconds. Confirm in the Model Studio console before making a call.
Video generation duration, in seconds. The current parameter value is fixed at 5 and cannot be modified. The model always generates videos with a duration of 5 seconds.prompt_extendbool (optional)Whether to enable intelligent prompt rewriting. When enabled, a large model is used to intelligently rewrite the input prompt. It significantly improves generation results for shorter prompts, but increases processing time.
  • true: Default value, enables intelligent rewriting.
  • false: Disables intelligent rewriting.
Example value: true.watermark bool (optional)Whether to add a watermark. The watermark is located in the lower-right corner of the image with the text "AI-generated".
  • false: Default value, no watermark is added.
  • true: Add a watermark.
Example value: false.seedinteger(optional)Random number seed. Value range: [0, 2147483647].If not specified, the system automatically generates a random seed. To improve the reproducibility of generation results, you are advised to use a fixed seed value.Note that due to the probabilistic nature of model generation, even with the same seed, identical generation results cannot be guaranteed.
  • First and Last Frame to Video
  • Use negative prompt
Generates a video based on the first frame, last frame, and prompt.
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image2video/video-synthesis' \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "wan2.2-kf2v-flash",
    "input": {
        "first_frame_url": "https://wanx.alicdn.com/material/20250318/first_frame.png",
        "last_frame_url": "https://wanx.alicdn.com/material/20250318/last_frame.png",
        "prompt": "写实风格,一只黑色小猫好奇地看向天空,镜头从平视逐渐上升,最后俯拍它的好奇的眼神。"
    },
    "parameters": {
        "resolution": "480P",
        "prompt_extend": true
    }
}'

Response parameters

output objectTask output information.

Property

task_id stringTask ID. Query validity: 24 hours.task_status stringStatus.

Enumerated values

  • PENDING: Task queuing
  • RUNNING: Task processing
  • SUCCEEDED: Task executed successfully
  • FAILED: Task execution failed
  • CANCELED: Task canceled
  • UNKNOWN: Task does not exist or status is unknown
request_idstringUnique request identifier. It can be used for tracing request details and troubleshooting.codestringError code returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.messagestringDetailed error information returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.
  • Success response
  • Error response
Please 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"
}

Step 2: Query the result by task ID

  • Singapore
  • Beijing
GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}When making calls, replace {WorkspaceId} with your actual workspace ID.
  • Polling recommendations: Video generation takes several minutes. We recommend using a polling mechanism with a reasonable query interval (such as 15 seconds) to obtain the results.
  • Task status transitions: PENDING (Queuing) → RUNNING (Processing) → SUCCEEDED (Success) / FAILED (Failed).
  • Result link: The video URL is returned after the task succeeds, valid for 24 hours. We recommend downloading it immediately after obtaining the URL and transferring it to permanent storage (such as Alibaba Cloud OSS).
  • task_id validity: 24 hours. Once it expires, the result can no longer be queried, and the API will return the task status as UNKNOWN.

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)Task ID.
  • Query task result
Replace 86ecf553-d340-4e21-xxxxxxxxx with the actual task_id.
API Keys differ across regions. See Obtain and configure an 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

outputobjectTask output information.

Property

task_id stringTask ID. Query validity: 24 hours.task_status stringStatus.

Enumerated values

  • PENDING: Task queuing
  • RUNNING: Task processing
  • SUCCEEDED: Task executed successfully
  • FAILED: Task execution failed
  • CANCELED: Task canceled
  • UNKNOWN: Task does not exist or status is unknown
Status transitions during polling:
  • PENDING (Queuing) → RUNNING (Processing) → SUCCEEDED (Success) / FAILED (Failed).
  • The status of the first query is usually PENDING (Queuing) or RUNNING (Processing).
  • When the status changes to SUCCEEDED, the response contains the URL of the generated video.
  • If the status is FAILED, check the error message and retry.
  • If the status is CANCELED, the task has been canceled. To continue, submit the task again.
  • If the status is UNKNOWN, the task does not exist or its status is unknown, which may occur when the task_id does not exist or the 24-hour validity period has expired.
submit_time stringTask submission time. The time zone is UTC+8, in the format YYYY-MM-DD HH:mm:ss.SSS.scheduled_time stringTask execution time. The time zone is UTC+8, in the format YYYY-MM-DD HH:mm:ss.SSS.end_time stringTask completion time. The time zone is UTC+8, in the format YYYY-MM-DD HH:mm:ss.SSS.video_urlstringVideo URL. Returned only when task_status is SUCCEEDED.The link is valid for 24 hours, and you can download the video via this URL. The video format is MP4 (H.264 encoding).orig_prompt stringThe original input prompt, corresponding to the request parameter prompt.actual_prompt stringWhen prompt smart rewriting is enabled, the actual optimized prompt used is returned. If this feature is not enabled, this field is not returned.codestringError code returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.messagestringDetailed error information returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.
usage objectOutput statistics. Only successful results are counted.

Property

video_duration integerThe duration of the generated video, in seconds. The enumerated value is 5. Billing formula: Fee = Video seconds × unit price.video_count integerThe number of generated videos. Fixed at 1.video_ratio stringCurrently, this value is returned only for the 2.1 model. The aspect ratio of the generated video, fixed at standard.SR integerCurrently, this value is returned only for the 2.2 model. The resolution tier of the generated video, with enumerated values 480, 720, and 1080.
request_idstringUnique request identifier. It can be used for tracing request details and troubleshooting.
  • Task executed successfully
  • Task execution failed
  • Task query expired
The video URL is retained for only 24 hours and will be automatically cleared after that. Save the generated video in a timely manner.
{
    "request_id": "ec016349-6b14-9ad6-8009-xxxxxx",
    "output": {
        "task_id": "3f21a745-9f4b-4588-b643-xxxxxx",
        "task_status": "SUCCEEDED",
        "submit_time": "2025-04-18 10:36:58.394",
        "scheduled_time": "2025-04-18 10:37:13.802",
        "end_time": "2025-04-18 10:45:23.004",
        "video_url": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/xxx.mp4?xxxxx",
        "orig_prompt": "写实风格,一只黑色小猫好奇地看向天空,镜头从平视逐渐上升,最后俯拍它的好奇的眼神。",
        "actual_prompt": "写实风格,一只黑色小猫好奇地看向天空,镜头从平视逐渐上升,最后俯拍它的好奇的眼神。小猫的黄色眼睛明亮有神,毛发光滑,胡须清晰可见。背景是简单的浅色墙面,突显小猫的黑色身影。近景特写,强调小猫的表情变化和眼神细节。"
    },
    "usage": {
        "video_duration": 5,
        "video_count": 1,
        "SR": 480
    }
}

Calling the DashScope SDK

The SDK parameter naming is basically the same as that of the HTTP API, and the parameter structure is encapsulated according to language characteristics. Since I2V tasks take a long time (usually 1-5 minutes), the SDK encapsulates the HTTP asynchronous call workflow at the underlying layer, supporting both synchronous and asynchronous call methods.
The actual time required depends on the number of queued tasks and service execution. Please wait patiently when retrieving the results.

Calling the Python SDK

Make sure the DashScope Python SDK version is no lower than 2.0.1 before running the following code.If the version is too old, errors such as "url error, please check url!" may occur. Refer to Install SDK to update it.
Set region according to the region where the model is located (pass it in when constructing the Client; the region values differ across regions):
  • Singapore
  • Beijing
region="ap-southeast-1"When making calls, replace {WorkspaceId} with your actual workspace ID.

Sample Code

  • Synchronous Call
  • Asynchronous Call
This example demonstrates the synchronous call method, including two image input methods: public URL and local file path.
Request example
import os
import dashscope
from dashscope import DashScopeError

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

"""
Requirements:
    dashscope python SDK >= 2.0.1
Install/Upgrade the SDK:
    pip install -U dashscope
"""

# ========== Image input methods (choose one) ==========
# [Method 1] Use a public image 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"

# [Method 2] Use a local file path (file:// + file path)
# Absolute path
# first_frame_url = "file://" + "/path/to/your/first_frame.png"  # Linux/macOS
# last_frame_url = "file://" + "C:/path/to/your/last_frame.png"  # Windows
# Or a relative path
# first_frame_url = "file://" + "./first_frame.png"              # Replace with your actual path.
# last_frame_url = "file://" + "./last_frame.png"                # Replace with your actual path.

def sample_sync_call_kf2v():
    print('please wait...')
    # generate is a one-step call (submits the task and waits for completion) that returns a completed Job.
    # first_frame_url and last_frame_url are input-section fields, not in the named signature; pass them through 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 status code: {e.status_code}")
        print(f"Error code: {e.code}")
        print(f"Error message: {e.message}")
        print("See the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code")

if __name__ == '__main__':
    sample_sync_call_kf2v()
Response example
video_url is valid for 24 hours. Download the video in a timely manner.
{
    "request_id": "a37fafc3-907c-96f3-95a6-5b2a8268a3fd",
    "task_id": "4dba0092-da13-42b2-afb1-0f7b8a0f4643",
    "status": "SUCCEEDED",
    "video_url": "https://dashscope-result-wlcb-acdr-1.oss-cn-wulanchabu-acdr-1.aliyuncs.com/xxx.mp4?xxxxx",
    "task_metrics": {
        "TOTAL": 1,
        "SUCCEEDED": 1,
        "FAILED": 0
    },
    "usage": {
        "video_count": 1,
        "video_duration": 5,
        "video_ratio": "standard"
    }
}

Calling the Java SDK

Make sure the DashScope Java SDK version is no lower than 2.20.9 before running the following code.If the version is too old, errors such as "url error, please check url!" may occur. Refer to Install SDK to update it.

Sample Code

  • Synchronous Call
  • Asynchronous Call
This example demonstrates the synchronous call method, including two image input methods: public URL and local file path.
Request example
// Copyright (c) Alibaba, Inc. and its affiliates.

// dashscope sdk >= 2.20.1
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.util.HashMap;
import java.util.Map;

public class Kf2vSyncIntl {

    static {
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // Get the DashScope API key (Model Studio API key) from the environment variable
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    /**
     * Image input method (choose one):
     *
     * [Method 1] Public URL
     */
    static String firstFrameUrl = "https://wanx.alicdn.com/material/20250318/first_frame.png";
    static String lastFrameUrl = "https://wanx.alicdn.com/material/20250318/last_frame.png";

     /**
     * [Method 2] Local file path (file://+absolute path or file:///+absolute path)
     */
    // static String firstFrameUrl = "file://" + "/your/path/to/first_frame.png";  // Linux/macOS
    // static String lastFrameUrl = "file:///" + "C:/path/to/your/img.png";        // Windows

    public static void syncCall() {

        Map<String, Object> parameters = new HashMap<>();
        parameters.put("prompt_extend", true);
        parameters.put("resolution", "720P");

        VideoSynthesis videoSynthesis = new VideoSynthesis();
        VideoSynthesisParam param =
                VideoSynthesisParam.builder()
                        .apiKey(apiKey)
                        .model("wan2.2-kf2v-flash")
                        .prompt("写实风格,一只黑色小猫好奇地看向天空,镜头从平视逐渐上升,最后俯拍它的好奇的眼神。")
                        .firstFrameUrl(firstFrameUrl)
                        .lastFrameUrl(lastFrameUrl)
                        .parameters(parameters)
                        .build();
        VideoSynthesisResult result = null;
        try {
            System.out.println("---sync call, please wait a moment----");
            result = videoSynthesis.call(param);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        } catch (InputRequiredException e) {
            throw new RuntimeException(e);
        }
        System.out.println(JsonUtils.toJson(result));
    }

    public static void main(String[] args) {
        syncCall();
    }
}
Sample Response
video_url is valid for 24 hours. Download the video in a timely manner.
{
    "request_id": "e6bb4517-c073-9c10-b748-dedb8c11bb41",
    "output": {
        "task_id": "984784fe-83c1-4fc4-88c7-52c2c1fa92a2",
        "task_status": "SUCCEEDED",
        "video_url": "https://dashscope-result-wlcb-acdr-1.oss-cn-wulanchabu-acdr-1.aliyuncs.com/xxx.mp4?xxxxx"
    },
    "usage": {
        "video_count": 1,
        "video_duration": 5,
        "video_ratio": "standard"
    }
}

Limits

  • Data validity: The task task_id and the video video_url are retained for only 24 hours. After expiration, they can no longer be queried or downloaded.
  • Audio support: Currently, only silent videos can be generated, and audio output is not supported. If needed, you can generate audio via speech synthesis.
  • Content moderation: The input prompt and images, as well as the output video, are all subject to content safety moderation. Content that violates the rules will return the "IPInfringementSuspect" or "DataInspectionFailed" error. For details, see Error codes.

Error codes

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

FAQ

Q: How do I generate a video with a specific aspect ratio (such as 3:4)?

A: The aspect ratio of the output video is determined by the input first frame image (first_frame_url), but the exact ratio cannot be guaranteed (for example, strictly 3:4); there will be some deviation.
  • Why is there a deviation? The model uses the ratio of the input image as the baseline and, combined with the total pixels of the set resolution tier (resolution), automatically calculates the closest valid resolution. Because the width and height of the video must be multiples of 16, the model fine-tunes the final resolution. Therefore, the output ratio cannot be strictly equal to 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 of approximately 920,000), the actual output is 816×1104 (aspect ratio ≈ 0.739, approximately 900,000 total pixels).
  • Best practices:
    • Input control: Use an image with the same ratio as the target whenever possible as the first frame input.
    • Post-processing: If you have strict ratio requirements, we recommend using an editing tool to perform simple cropping or black-bar padding after the video is generated.

Q: How do I obtain the access domain whitelist for video storage?

A: Videos generated by the model are stored in Alibaba Cloud OSS, and the API returns a temporary public URL. If you need to configure a firewall whitelist for the download URL, note that: because the underlying storage changes dynamically based on business conditions, this documentation does not provide a fixed OSS domain whitelist to prevent expired information from affecting access. If you have security control requirements, contact your account manager to obtain the latest OSS domain list.