Wan -image-to-video-first and last frames API reference(2.2)

Updated at:

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.

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.com to https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com
  • Singapore: from https://dashscope-intl.aliyuncs.com to https://{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

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, use the returned task_id to query the result. The task_id is valid for 24 hours. Do not create duplicate tasks. Instead, use polling to retrieve the result.
  • For guidance for beginners, see Call APIs with Postman or cURL.

Request parameters

Request headers

Content-Type string (Required)

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

Authorization string (Required)

Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.

X-DashScope-Async string (Required)

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

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

Request body

model string (Required)

The name of the model. Example: wan2.2-kf2v-flash.

For details, see the Model Studio console.

input object (Required)

Contains the primary input for the task, such as the prompt.

Properties

prompt string (Optional)

The text prompt. Supports both Chinese and English. The maximum length is 800 characters. Both Chinese characters and letters count as a single character. Text exceeding this limit is truncated.

If there are significant changes in the subject or scene between the first and last frames, we recommend describing the transition process, such as camera movement (e.g., "camera moves to the left") or subject movement (e.g., "a person runs forward").

Example: "A small black cat looks up at the sky curiously. The camera gradually rises from eye level and finally captures its curious gaze from a top-down view."

For tips on writing effective prompts, see the Prompt guide for text-to-video and image-to-video.

negative_prompt string (Optional)

A negative prompt that describes content to exclude from the video, which helps constrain the output.

Supports both Chinese and English. The maximum length is 500 characters. Text exceeding this limit is truncated.

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

first_frame_url string (Required)

The URL or Base64-encoded data of the first frame image. The aspect ratio of the output video is determined by this image.

Image requirements:

  • Format: JPEG, JPG, PNG (alpha channel not supported), BMP, WEBP.
  • Resolution: The width and height must be between 240 and 8,000 pixels.
  • File size: No more than 10 MB.

Supported input formats:

  1. Public URL:

  2. Temporary URL:

  3. Base64-encoded string:

    • Data format: data:{MIME_type};base64,{base64_data}
    • Example: data:image/png;base64,GDU7MtCZzEbTbmRZ...... (The encoded string is truncated for brevity.)
    • For details, see How to input images.

last_frame_url string (Optional)

The URL or Base64-encoded data of the last frame image.

Image requirements:

  • Format: JPEG, JPG, PNG (alpha channel not supported), BMP, WEBP.
  • Resolution: The width and height must be between 240 and 8,000 pixels. The resolution of the last frame can be different from the first frame, and their resolutions or aspect ratios do not need to match.
  • File size: No more than 10 MB.

Supported input formats:

  1. Public URL:

  2. Temporary URL:

  3. Base64-encoded string:

    • Data format: data:{MIME_type};base64,{base64_data}
    • Example: data:image/png;base64,GDU7MtCZ...... (The encoded string is truncated for brevity.)
    • For details, see How to input images.

template string (Optional)

The name of the video effect template. When you use this parameter, you only need to provide first_frame_url.

Different models support different effect templates. To avoid call failures, refer to the Wan image-to-video effect list before making a call.

Example: hanfu-1, which applies the "Graceful Tang Dynasty" effect.

parameters object (Optional)

Video processing parameters.

Properties

resolution string (Optional)

ImportantThe resolution parameter directly affects the cost. For the same model, the cost hierarchy is 1080P > 720P > 480P. Confirm the pricing in the Model Studio console before making a call.

The resolution of the generated video. This parameter adjusts the definition (total pixels) without changing its aspect ratio.

The default value and available values for this parameter depend on the model parameter, as described below:

  • wan2.2-kf2v-flash: Possible values are 480P, 720P, and 1080P. The default value is 720P.
  • wanx2.1-kf2v-plus: The only possible value is 720P. The default value is 720P.

Example: 720P

duration integer (Optional)

ImportantThe duration parameter directly affects the cost, which is billed per second. Confirm the pricing in the Model Studio console before making a call.

This value is fixed at 5.

prompt_extendbool (Optional)

Specifies whether to enable prompt rewriting. When enabled, a large language model (LLM) intelligently rewrites the input prompt. This can significantly improve results for short prompts but increases latency.

  • true: Default value. Enables prompt rewriting.
  • false: Disables prompt rewriting.

Example: true

watermark bool (Optional)

Specifies whether to add a watermark with the text "AI-generated" to the bottom-right corner of the video.

  • false: Default value. Does not add a watermark.
  • true: Adds a watermark.

Example: false

seed integer (Optional)

The random number seed must be an integer in the range [0, 2147483647].

If not specified, a random seed is generated. A fixed seed improves reproducibility.

Because model generation is probabilistic, the same seed does not guarantee identical results.

First and last frames

Generates a video based on a first frame, a last frame, and a prompt.

# The URL below is for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
curl --location 'https://{WorkspaceId}.cn-beijing.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": "Realistic style, a small black cat looks up at the sky curiously, the camera gradually rises from eye level, and finally captures its curious gaze from a top-down view."
    },
    "parameters": {
        "resolution": "480P",
        "prompt_extend": true
    }
}'

Base64 encoding

The 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.

# The URL below is for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
curl --location 'https://{WorkspaceId}.cn-beijing.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": "wanx2.1-kf2v-plus",
    "input": {
        "first_frame_url": "data:image/png;base64,GDU7MtCZzEbTbmRZ......",
        "last_frame_url": "data:image/png;base64,VBORw0KGgoAAAANSUh......",
        "prompt": "Realistic style, a small black cat looks up at the sky curiously, the camera gradually rises from eye level, and finally captures its curious gaze from a top-down view."
    },
    "parameters": {
        "resolution": "720P",
        "prompt_extend": true
    }
}'

Video effects

You must provide the first_frame_url and template parameters. The prompt and last_frame_url parameters are not required.

Different models support different effect templates. To avoid call failures, refer to the Wan image-to-video effect list before making a call.

# The URL below is for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
curl --location 'https://{WorkspaceId}.cn-beijing.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": "wanx2.1-kf2v-plus",
    "input": {
        "first_frame_url": "https://ty-yuanfang.oss-cn-hangzhou.aliyuncs.com/lizhengjia.lzj/tmp/11.png",
        "template": "hanfu-1"
    },
    "parameters": {
        "resolution": "720P",
        "prompt_extend": true
    }
}'

Negative prompt

Use the negative_prompt parameter to exclude certain elements, such as people, from the generated video.

# The URL below is for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
curl --location 'https://{WorkspaceId}.cn-beijing.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": "wanx2.1-kf2v-plus",
    "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": "Realistic style, a small black cat looks up at the sky curiously, the camera gradually rises from eye level, and finally captures its curious gaze from a top-down view.",
        "negative_prompt": "people"
    },
    "parameters": {
        "resolution": "720P",
        "prompt_extend": true
    }
}'

Response parameters

output object

The output information for the task.

Properties

task_id string

The task ID. Valid for queries for 24 hours.

task_status string

The status of the task.

Enumeration values

  • PENDING
  • RUNNING
  • SUCCEEDED
  • FAILED
  • CANCELED
  • UNKNOWN: The task does not exist or its status is unknown.

request_id string

Unique request identifier for tracing and troubleshooting.

code string

Error code. Returned only for failed requests. See Error codes.

message string

Detailed error message. Returned only for failed requests. See Error codes.

Successful response

Save the task_id to query the task status and result.

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

Error response

Task creation failed. See Error codes.

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

Step 2: Query the result

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. Use a polling mechanism with a reasonable interval, such as 15 seconds.
  • Task state transition: PENDING → RUNNING → SUCCEEDED or FAILED.
  • Result link: After a task succeeds, a video URL valid for 24 hours is returned. Download and save the video to permanent storage, such as OSS.
  • task_idvalidity: 24 hours. After this period, queries return the task status as UNKNOWN.
  • RPS limit: The default RPS for the query API is 20. For higher-frequency queries or event notifications, we recommend that you configure an asynchronous task callback.
  • More operations: For batch queries, task cancellation, and other operations, see Manage asynchronous tasks.

Request parameters

Request headers

Authorization string (Required)

Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.

Path parameters

task_id string (Required)

The ID of the task.

Query task result

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

If you use a model in the Singapore region, replace base_url with https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx, where {WorkspaceId} is your actual workspace ID.

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

Response parameters

outputobject

The output information for the task.

Properties

task_id string

The task ID. Valid for queries for 24 hours.

task_status string

The status of the task.

Enumeration values

  • PENDING
  • RUNNING
  • SUCCEEDED
  • FAILED
  • CANCELED
  • UNKNOWN: The task does not exist or its status is unknown.
State transitions during polling:
  • PENDING → RUNNING → SUCCEEDED or FAILED.
  • The initial query status is usually PENDING or RUNNING.
  • When the status changes to SUCCEEDED, the response contains the generated video URL.
  • If the status is FAILED, check the error message and retry the task.

submit_time string

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

scheduled_time string

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

end_time string

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

video_url string

URL of the generated video. Returned only when task_status is SUCCEEDED.

Valid for 24 hours. The video is in MP4 format with H.264 encoding.

orig_prompt string

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

actual_prompt string

The optimized prompt used when prompt rewriting is enabled. Not returned when disabled.

code string

Error code. Returned only for failed requests. See Error codes.

message string

Detailed error message. Returned only for failed requests. See Error codes.

usage object

Task usage statistics. Only successful tasks are billed.

Properties

video_duration integer

The duration of the generated video in seconds, which is always 5. Billing formula: Cost = Video seconds × Unit price.

video_count integer

The number of videos generated. This value is fixed at 1.

video_ratio string

This value is currently returned only by the 2.1 model. The aspect ratio of the generated video, which is fixed at standard.

SR integer

This value is currently returned only by the 2.2 model. The resolution tier of the generated video. Possible values are 480, 720, and 1080.

request_id string

Unique request identifier for tracing and troubleshooting.

Task succeeded

Video URLs are valid for only 24 hours and then automatically purged. Save generated videos promptly.

{
    "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": "Realistic style, a small black cat looks up at the sky curiously, the camera gradually rises from eye level, and finally captures its curious gaze from a top-down view.",
        "actual_prompt": "Realistic style, a small black cat looks up at the sky curiously, the camera gradually rises from eye level, and finally captures its curious gaze from a top-down view. The cat's yellow eyes are bright and expressive, its fur is smooth, and its whiskers are clearly visible. The background is a simple light-colored wall, highlighting the cat's black silhouette. A close-up shot emphasizes the changes in the cat's expression and the details of its eyes."
    },
    "usage": {
        "video_duration": 5,
        "video_count": 1,
        "SR": 480
    }
}

Task failed

When a task fails, task_status is FAILED with an error code and message. See Error codes.

{
    "request_id": "e5d70b02-ebd3-98ce-9fe8-759d7d7b107d",
    "output": {
        "task_id": "86ecf553-d340-4e21-af6e-a0c6a421c010",
        "task_status": "FAILED",
        "code": "InvalidParameter",
        "message": "The size is not match xxxxxx"
    }
}

Task query expired

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

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

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 least1.23.8.

Older versions may trigger errors such as "url error, please check url!". See Install SDK to update.

Set the base_http_api_url based on the model's region:

Beijing

dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'

Replace {WorkspaceId} with your actual workspace ID.

Singapore

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

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
from http import HTTPStatus
from dashscope import VideoSynthesis
import mimetypes
import dashscope

# The URL below is for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'

# 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://help.aliyun.com/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")

# --- Helper function for Base64 encoding ---
# Format: 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("Unsupported or unrecognized image format")
    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}"

"""
Image input methods:
Choose one of the following.

1. Public URL - Suitable for publicly accessible images.
2. Local file - Suitable for local development and testing.
3. Base64 encoding - Suitable for private images or when encrypted transmission is required.
"""

# [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 (supports absolute and relative paths)
# Format: file:// + file path
# Example (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
# Example (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.

# [Method 3] Use a Base64-encoded image
# first_frame_url = encode_file("./first_frame.png")            # Replace with your actual path.
# last_frame_url = encode_file("./last_frame.png")              # Replace with your actual path.

def sample_sync_call_kf2v():
    print('please wait...')
    rsp = VideoSynthesis.call(api_key=api_key,
                              model="wan2.2-kf2v-flash",
                              prompt="Realistic style, a small black cat looks up at the sky curiously, the camera gradually rises from eye level, and finally captures its curious gaze from a top-down view.",
                              first_frame_url=first_frame_url,
                              last_frame_url=last_frame_url,
                              resolution="720P",
                              prompt_extend=True)
    print(rsp)
    if rsp.status_code == HTTPStatus.OK:
        print(rsp.output.video_url)
    else:
        print('Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))

if __name__ == '__main__':
    sample_sync_call_kf2v()
Response example

The video_url is valid for 24 hours. Please download the video within this period.

{
    "status_code": 200,
    "request_id": "efa545b3-f95c-9e3a-a3b6-xxxxxx",
    "code": null,
    "message": "",
    "output": {
        "task_id": "721164c6-8619-4a35-a6d9-xxxxxx",
        "task_status": "SUCCEEDED",
        "video_url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.mp4?xxxxx",
        "submit_time": "2025-02-12 11:03:30.701",
        "scheduled_time": "2025-02-12 11:06:05.378",
        "end_time": "2025-02-12 11:12:18.853",
        "orig_prompt": "Realistic style, a small black cat looks up at the sky curiously, the camera gradually rises from eye level, and finally captures its curious gaze from a top-down view.",
        "actual_prompt": "Realistic style, a small black cat looks up at the sky curiously, the camera gradually rises from eye level, and finally captures its curious gaze from a top-down view. The cat's fur is jet-black and glossy, its eyes are large and bright with golden pupils. It looks up with its ears pricked, appearing exceptionally focused. After the camera moves up, the cat turns to face the camera, its eyes filled with curiosity and alertness. The background is simple, highlighting the cat's detailed features. A close-up shot with soft, natural light."
    },
    "usage": {
        "video_count": 1,
        "video_duration": 5,
        "video_ratio": "standard"
    }
}

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
import os
from http import HTTPStatus
from dashscope import VideoSynthesis
import dashscope

# The URL below is for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'

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

# If you have not configured an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"
# API keys for the China (Singapore) and China (Beijing) regions are different. To get an API key, see https://help.aliyun.com/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")

# Use a publicly accessible 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"

def sample_async_call_kf2v():
    # Make an asynchronous call, which returns a task_id.
    rsp = VideoSynthesis.async_call(api_key=api_key,
                                    model="wan2.2-kf2v-flash",
                                    prompt="Realistic style, a small black cat looks up at the sky curiously, the camera gradually rises from eye level, and finally captures its curious gaze from a top-down view.",
                                    first_frame_url=first_frame_url,
                                    last_frame_url=last_frame_url,
                                    resolution="720P",
                                    prompt_extend=True)
    print(rsp)
    if rsp.status_code == HTTPStatus.OK:
        print("task_id: %s" % rsp.output.task_id)
    else:
        print('Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))

    # Get the asynchronous task status.
    status = VideoSynthesis.fetch(task=rsp, api_key=api_key)
    if status.status_code == HTTPStatus.OK:
        print(status.output.task_status)  # check the task status
    else:
        print('Failed, status_code: %s, code: %s, message: %s' %
              (status.status_code, status.code, status.message))

    # Wait for the asynchronous task to complete.
    rsp = VideoSynthesis.wait(task=rsp, api_key=api_key)
    print(rsp)
    if rsp.status_code == HTTPStatus.OK:
        print(rsp.output.video_url)
    else:
        print('Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))

if __name__ == '__main__':
    sample_async_call_kf2v()
Response example
  1. Response upon task creation
{
    "status_code": 200,
    "request_id": "c86ff7ba-8377-917a-90ed-xxxxxx",
    "code": "",
    "message": "",
    "output": {
        "task_id": "721164c6-8619-4a35-a6d9-xxxxxx",
        "task_status": "PENDING",
        "video_url": ""
    },
    "usage": null
}
  1. Example response for a completed task

The video_url is valid for 24 hours. Please download the video within this period.

{
    "status_code": 200,
    "request_id": "efa545b3-f95c-9e3a-a3b6-xxxxxx",
    "code": null,
    "message": "",
    "output": {
        "task_id": "721164c6-8619-4a35-a6d9-xxxxxx",
        "task_status": "SUCCEEDED",
        "video_url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.mp4?xxxxx",
        "submit_time": "2025-02-12 11:03:30.701",
        "scheduled_time": "2025-02-12 11:06:05.378",
        "end_time": "2025-02-12 11:12:18.853",
        "orig_prompt": "Realistic style, a small black cat looks up at the sky curiously, the camera gradually rises from eye level, and finally captures its curious gaze from a top-down view.",
        "actual_prompt": "Realistic style, a small black cat looks up at the sky curiously, the camera gradually rises from eye level, and finally captures its curious gaze from a top-down view. The cat's fur is jet-black and glossy, its eyes are large and bright with golden pupils. It looks up with its ears pricked, appearing exceptionally focused. After the camera moves up, the cat turns to face the camera, its eyes filled with curiosity and alertness. The background is simple, highlighting the cat's detailed features. A close-up shot with soft, natural light."
    },
    "usage": {
        "video_count": 1,
        "video_duration": 5,
        "video_ratio": "standard"
    }
}

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;

/**
 * Requirements:
 *      DashScope Java SDK >= 2.20.9
 * To update the Maven dependency, visit:
 *      https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
 */
public class Kf2vSync {

    static {
        // The URL below is for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
    }

    // If you have not configured an environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx"
    // API keys for the China (Singapore) and China (Beijing) regions are different. To get an API key, see https://help.aliyun.com/en/model-studio/get-api-key
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    /**
     * Image input methods (choose one):
     *
     * 1. Public URL - Suitable for publicly accessible images.
     * 2. Local file - Suitable for local development and testing.
     * 3. Base64 encoding - Suitable for private images or when encrypted transmission is required.
     */

    //[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

    //[Method 3] Base64 encoding
    // static String firstFrameUrl = Kf2vSync.encodeFile("/your/path/to/first_frame.png");
    // static String lastFrameUrl = Kf2vSync.encodeFile("/your/path/to/last_frame.png");

    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("Realistic style, a small black cat looks up at the sky curiously, the camera gradually rises from eye level, and finally captures its curious gaze from a top-down view.")
                        .firstFrameUrl(firstFrameUrl)
                        .lastFrameUrl(lastFrameUrl)
                        .parameters(parameters)
                        .build();
        VideoSynthesisResult result = null;
        try {
            // Making a synchronous call. This may take 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));
    }

    /**
     * Encodes a file into a Base64 string.
     * @param filePath The path to the file.
     * @return A Base64 string in the format: data:{MIME_type};base64,{base64_data}
     */
    public static String encodeFile(String filePath) {
        Path path = Paths.get(filePath);
        if (!Files.exists(path)) {
            throw new IllegalArgumentException("File not found: " + filePath);
        }
        // Detect MIME type.
        String mimeType = null;
        try {
            mimeType = Files.probeContentType(path);
        } catch (IOException e) {
            throw new IllegalArgumentException("Cannot detect file type: " + filePath);
        }
        if (mimeType == null || !mimeType.startsWith("image/")) {
            throw new IllegalArgumentException("Unsupported or unrecognized image format");
        }
        // Read file content and encode.
        byte[] fileBytes = null;
        try{
            fileBytes = Files.readAllBytes(path);
        } catch (IOException e) {
            throw new IllegalArgumentException("Cannot read file content: " + filePath);
        }

        String encodedString = Base64.getEncoder().encodeToString(fileBytes);
        return "data:" + mimeType + ";base64," + encodedString;
    }

    public static void main(String[] args) {
        syncCall();
    }
}
Response example

The video_url is valid for 24 hours. Please download the video within this period.

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

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;

/**
 * Requirements:
 *      DashScope Java SDK >= 2.20.9
 * To update the Maven dependency, visit:
 *      https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
 */

public class Kf2vAsync {

    static {
        // The URL below is for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
    }

    // If you have not configured an environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx"
    // API keys for the China (Singapore) and China (Beijing) regions are different. To get an API key, see https://help.aliyun.com/en/model-studio/get-api-key
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // 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";

    public static void asyncCall(){

        // Set parameters.
        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("Realistic style, a small black cat looks up at the sky curiously, the camera gradually rises from eye level, and finally captures its curious gaze from a top-down view.")
                        .firstFrameUrl(firstFrameUrl)
                        .lastFrameUrl(lastFrameUrl)
                        .parameters(parameters)
                        .build();
        VideoSynthesisResult result = null;
        try {
            // Making an asynchronous call.
            result = videoSynthesis.asyncCall(param);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        } catch (InputRequiredException e) {
            throw new RuntimeException(e);
        }
        System.out.println(JsonUtils.toJson(result));

        String taskId = result.getOutput().getTaskId();

        System.out.println("taskId=" + taskId);

        try {
            result = videoSynthesis.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()));
    }

    // Get the list of tasks.
    public static void listTask() throws ApiException, NoApiKeyException {
        VideoSynthesis is = new VideoSynthesis();
        AsyncTaskListParam param = AsyncTaskListParam.builder().build();
        param.setApiKey(apiKey);
        VideoSynthesisListResult result = is.list(param);
        System.out.println(result);
    }

    // Fetch the result of a single task.
    public static void fetchTask(String taskId) throws ApiException, NoApiKeyException {
        VideoSynthesis is = new VideoSynthesis();
        // If DASHSCOPE_API_KEY is set as an environment variable, apiKey can be null.
        VideoSynthesisResult result = is.fetch(taskId, apiKey);
        System.out.println(result.getOutput());
        System.out.println(result.getUsage());
    }

    public static void main(String[] args){
        asyncCall();
    }
}
Response example
  1. Response upon task creation
{
    "request_id": "5dbf9dc5-4f4c-9605-85ea-xxxxxxxx",
    "output": {
        "task_id": "7277e20e-aa01-4709-xxxxxxxx",
        "task_status": "PENDING"
    }
}
  1. Example response for a completed task

The video_url is valid for 24 hours. Please download the video within this period.

{
    "request_id": "1625235c-c13e-93ec-aff7-xxxxxxxx",
    "output": {
        "task_id": "464a5e46-79a6-46fd-9823-xxxxxxxx",
        "task_status": "SUCCEEDED",
        "video_url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.mp4?xxxxxx"
    },
    "usage": {
        "video_count": 1,
        "video_duration": 5,
        "video_ratio": "standard"
    }
}

Limitations

  • Data retention: The task task_id and video video_url are 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 input image's aspect ratio as a baseline and calculates the closest valid resolution based on the total pixels of the selected resolution setting. Because the video's width and height must be multiples of 16, the model makes minor adjustments to the final resolution.

    • For example, if you provide a 750×1000 input image (an aspect ratio of 3:4 or 0.75) and set resolution to "720P" (targeting approximately 920,000 pixels), the actual output might be 816×1104 (an aspect ratio of approximately 0.739, with about 900,000 pixels).
  • Recommendations:
    • 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. 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.