Wan 2.7 - image-to-video API

Updated at:

The Wan 2.7 image-to-video model supports multimodal input (text, images, audio, and video) and performs three tasks: first-frame-to-video, first-and-last-frame-to-video, and video continuation .

References: User guide

NoteThe newly launched image-to-video API (wan2.7 model) supports all three tasks and is recommended as the first choice.

The earlier image-to-video from first frame API (wan2.6 and earlier models) supports only first-frame-to-video.

Availability

To ensure successful calls, the model, endpoint URL, and API key must all belong to the same region. Cross-region calls fail.

NoteThe sample code in this topic applies to the Beijing region.

ImportantAlibaba Cloud Model Studio has released workspace-specific domains for the China (Beijing) and Singapore regions. The dedicated domains deliver superior performance and higher stability for inference requests. We recommend that you migrate to the new domains:

  • China (Beijing) region: from https://dashscope.aliyuncs.com to https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com
  • Singapore region: from https://dashscope-intl.aliyuncs.com to https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com

{WorkspaceId} is your workspace ID, which you can view on the Workspace Details page in the Alibaba Cloud Model Studio console. The existing domains remain fully functional.

HTTP

ImportantThis API uses the new image-to-video protocol and supports only the wan2.7 model.

Image-to-video tasks take a long time (typically 1 to 5 minutes), so the API uses asynchronous invocation. The entire process consists of two core steps: "create a task -> poll for the result", as follows:

Step 1: Create a task and get the task ID

Beijing

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

Singapore

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

Replace {WorkspaceId} with your actual workspace ID.

Note

  • 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 duplicate tasks. Use polling to retrieve the result.
  • For beginner guidance, see Postman.

Request parameters

Content-Typestring(Required)

The request content type. This parameter must be set to application/json.

Authorizationstring(Required)

Request authentication. This API uses an Alibaba Cloud Model Studio API key for authentication. Example: Bearer sk-xxxx.

X-DashScope-Asyncstring(Required)

The asynchronous processing configuration parameter. HTTP requests support only asynchronous calls, and this parameter must be set to 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 model name. For the list of models and prices, see Model pricing.

Example: wan2.7-i2v-2026-04-25.

input object (Required)

Basic input information, such as the prompt.

Properties

prompt string (Optional)

The text prompt, which describes the elements and visual characteristics that you want in the generated video.

Chinese and English are supported, up to 5,000 characters. Each Chinese character or letter counts as one character, and the part beyond the limit is automatically truncated.

Example: A kitten running on the grass.

For tips on how to write prompts, see the Text-to-video/image-to-video prompt guide.

negative_prompt string (Optional)

The negative prompt, which describes the content that you do not want to see in the video. It can be used to constrain the video output.

Chinese and English are supported, up to 500 characters, and the part beyond the limit is automatically truncated.

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

media array (Required)

The list of media assets, which specifies the reference materials (images, audio, and video) required for video generation.

Each element of the array is a media object that contains the type and url fields.

Asset combinations

Only the following specific asset combinations are supported. Invalid combinations return an error.

  • Video generation from the first frame:

    • First frame: first_frame
    • First frame + audio: first_frame+driving_audio
  • Video generation from the first and last frames:

    • First frame + last frame: first_frame+last_frame
    • First frame + last frame + audio: first_frame+last_frame+driving_audio
  • Video continuation:

    • First video clip continuation: first_clip
    • First video clip + last frame continuation: first_clip+last_frame

Properties

type string (Required)

The media asset type. Valid values:

  • first_frame: first frame.
  • last_frame: last frame.
  • driving_audio: driving audio.
  • first_clip: first video clip.

Usage limit: each type can appear at most once in the media array (for example, you cannot pass two first_frame assets).

url string (Required)

The URL of the media asset. Assets include images, audio, and video.

Pass an image (type=first_frame or last_frame)

The URL of the first or last frame, or Base64-encoded data. Video generation from the first frame and from the first and last frames are currently supported.

Image limits:

  • Format: JPEG, JPG, PNG (transparent channel not supported), BMP, WEBP.
  • Resolution: The width and height are in the range of [240, 8000] pixels.
  • Aspect ratio: 1:8 to 8:1.
  • File size: up to 20 MB.

Supported input formats:

  1. Public URL:

  2. Temporary URL:

  3. A string of the image encoded in Base64:

    • Data format: data:{MIME_type};base64,{base64_data}.

    • Example: data:image/png;base64,GDU7MtCZzEbTbmRZ...... (The example is truncated and is for demonstration purposes only).

      Base64-encoded data format

      Format: data:{MIME_type};base64,{base64_data} .

      • {base64_data}: the string of the image file encoded in Base64.
      • {MIME_type}: the media type of the image, which must correspond to the file format.

      Image format

      MIME Type

      JPEG

      image/jpeg

      JPG

      image/jpeg

      PNG

      image/png

      BMP

      image/bmp

      WEBP

      image/webp

Pass audio (type=driving_audio)

The URL of the audio file.

  • With audio: The model uses the audio as the driving source to generate the video (such as lip sync and action beat syncing).
  • Without audio: The model automatically generates matching background music or sound effects based on the video content.

Audio limits:

  • Format: wav, mp3.
  • Duration: 2 s to 30 s.
  • File size: up to 15 MB.
  • Truncation: If the audio length exceeds the duration value (for example, 5 seconds), the first 5 seconds are automatically captured and the rest is discarded. If the audio is shorter than the video duration, the part of the video beyond the audio length is silent. For example, if the audio is 3 seconds and the video duration is 5 seconds, the first 3 seconds of the output video have sound and the last 2 seconds are silent.

Supported input formats:

  1. Public URL:

  2. Temporary URL:

Pass a video (type=first_clip)

The URL of the video file. The model generates a continuation based on the video content. The upper limit of the continuation duration is controlled by the duration parameter.

For example, when duration=15, if the input video is 3 seconds, the model generates a 12-second continuation, and the final output video is 15 seconds in total and billed as 15 seconds.

Video limits:

  • Format: mp4, mov.
  • Duration: 2 s to 10 s.
  • Resolution: The width and height are in the range of [240, 4096] pixels.
  • Aspect ratio: 1:8 to 8:1.
  • File size: up to 100 MB.

Supported input formats:

  1. Public URL:

  2. Temporary URL:

parameters object (Optional)

Video processing parameters, such as setting the video resolution, setting the video duration, enabling smart prompt rewriting, and adding a watermark.

Properties

resolution string (Optional)

ImportantResolution directly affects the cost. Before calling the API, check the Model pricing.

The resolution tier of the generated video, which controls the video clarity (total pixels).

Based on the selected resolution tier, the model automatically scales the video to a similar total pixel count. The video aspect ratio follows the input material (first frame or first video clip) as closely as possible. For more information, see the FAQ.

Valid values:

  • 720P
  • 1080P (default)

duration integer (Optional)

ImportantDuration directly affects the cost. Billing is per second. Before calling the API, check the Model pricing.

The duration of the generated video, in seconds.

An integer in the range [2, 15]. Default: 5.

prompt_extendboolean (Optional)

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

  • true: default. Smart rewriting is enabled.
  • false: Smart rewriting is disabled.

watermark boolean (Optional)

Whether to add a watermark. The watermark appears in the lower-right corner of the video with the fixed text "AI Generated".

  • false: default. No watermark is added.
  • true: A watermark is added.

seedinteger(Optional)

The random number seed, in the range [0, 2147483647].

If not specified, the system automatically generates a random seed. To improve the reproducibility of the results, we recommend that you fix the seed value.

Note that model generation is probabilistic. Even with the same seed, identical results are not guaranteed for each generation.

Video generation from the first frame

Generate a video based on a first frame image and audio.


# 以下为华北2(北京)地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis' \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "wan2.7-i2v-2026-04-25",
    "input": {
        "prompt": "一幅都市奇幻艺术的场景。一个充满动感的涂鸦艺术角色。一个由喷漆所画成的少年,正从一面混凝土墙上活过来。他一边用极快的语速演唱一首英文rap,一边摆着一个经典的、充满活力的说唱歌手姿势。场景设定在夜晚一个充满都市感的铁路桥下。灯光来自一盏孤零零的街灯,营造出电影般的氛围,充满高能量和惊人的细节。视频的音频部分完全由rap构成,没有其他对话或杂音。",
        "media": [
            {
                "type": "first_frame",
                "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png"
            },
            {
                "type": "driving_audio",
                "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/ozwpvi/rap.mp3"

            }
        ]
    },
    "parameters": {
        "resolution": "720P",
        "duration": 10,
        "prompt_extend": true,
        "watermark": true
    }
}'

Video generation from the first and last frames

Pass a first frame and a last frame to generate a video.


# 以下为华北2(北京)地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis' \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "wan2.7-i2v-2026-04-25",
    "input": {
        "prompt": "写实风格,一只小黑猫好奇地仰望天空,镜头从平视角度逐渐升高,最后以俯视角度捕捉到它好奇的眼神。",
        "media": [
            {
                "type": "first_frame",
                "url": "https://wanx.alicdn.com/material/20250318/first_frame.png"
            },
            {
                "type": "last_frame",
                "url": "https://wanx.alicdn.com/material/20250318/last_frame.png"
            }
        ]
    },
    "parameters": {
        "resolution": "720P",
        "duration": 10,
        "prompt_extend": false,
        "watermark": true
    }
}'

Video continuation

Generate subsequent content based on an initial video clip.


# 以下为华北2(北京)地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis' \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "wan2.7-i2v-2026-04-25",
    "input": {
        "prompt": "一个女孩对镜自拍,自拍结束后背着书包出门",
        "media": [
            {
                "type": "first_clip",
                "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260129/hfugmr/wan-r2v-role1.mp4"
            }
        ]
    },
    "parameters": {
        "resolution": "720P",
        "duration": 10,
        "prompt_extend": true,
        "watermark": true
    }
}'

Response parameters

output object

Task output information.

Properties

task_id string

The task ID. Valid for queries for 24 hours.

task_status string

The task status.

Enumeration values

  • PENDING: The task is queued.
  • RUNNING: The task is being processed.
  • SUCCEEDED: The task succeeded.
  • FAILED: The task failed.
  • CANCELED: The task was canceled.
  • UNKNOWN: The task does not exist or its status is unknown.

request_idstring

The unique request identifier, which can be used for request tracing and troubleshooting.

codestring

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

messagestring

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

Successful response

Save the task_id, which is used 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 to resolve the issue.

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

Step 2: Query the result by task ID

Beijing

GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_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. We recommend that you use a polling mechanism with a reasonable query interval (such as 15 seconds) to obtain the result.
  • Task state transition: PENDING (queued) → RUNNING (processing) → SUCCEEDED (success) / FAILED (failure).
  • Result link: After the task succeeds, a video URL is returned, which is valid for 24 hours. We recommend that you download the video immediately after obtaining the URL and save 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 returns 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 operations such as batch queries and task cancellation, see Manage asynchronous tasks.

Request parameters

Headers

Authorizationstring(Required)

Request authentication. This API uses an Alibaba Cloud Model Studio API key for authentication. Example: Bearer sk-xxxx.

Path parameters

task_id string(Required)

The task ID.

Query task result

Replace {task_id} with the value of task_id returned by the previous API call. The task_id is valid for queries for 24 hours. Replace {WorkspaceId} with your actual workspace ID.

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

Response parameters

outputobject

Task output information.

Properties

task_id string

The task ID. Valid for queries for 24 hours.

task_status string

The task status.

Enumeration values

  • PENDING: The task is queued.
  • RUNNING: The task is being processed.
  • SUCCEEDED: The task succeeded.
  • FAILED: The task failed.
  • CANCELED: The task was canceled.
  • UNKNOWN: The task does not exist or its status is unknown.
State transitions during polling:
  • PENDING (queued) → RUNNING (processing) → SUCCEEDED (success) / FAILED (failure).
  • The status of the first query is usually PENDING (queued) or RUNNING (processing).
  • 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.
  • 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. This may occur when the task_id does not exist or the 24-hour validity period has expired.

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 was executed. 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.

video_urlstring

The video URL. Returned only when task_status is SUCCEEDED.

The link is valid for 24 hours, and you can download the video from this URL. The video is in MP4 format (H.264 encoding).

orig_prompt string

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

codestring

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

messagestring

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

usage object

Output statistics, counted only for successful results.

Properties

input_video_duration integer

The duration of the input video, in seconds.

output_video_duration integer

The duration of the output video, in seconds.

duration integer

The total video duration, used for billing.

SR integer

The resolution tier of the output video. Example: 720.

video_count integer

The number of output videos. Fixed at 1.

request_idstring

The unique request identifier, which can be used for request tracing and troubleshooting.

Task succeeded

The video URL is retained for only 24 hours and is automatically cleared after it expires. Save the generated video in a timely manner.

{
    "request_id": "2ca1c497-f9e0-449d-9a3f-xxxxxx",
    "output": {
        "task_id": "af6efbc0-4bef-4194-8246-xxxxxx",
        "task_status": "SUCCEEDED",
        "submit_time": "2025-09-25 11:07:28.590",
        "scheduled_time": "2025-09-25 11:07:35.349",
        "end_time": "2025-09-25 11:17:11.650",
        "orig_prompt": "一幅都市奇幻艺术的场景。一个充满动感的涂鸦艺术角色。一个由喷漆所画成的少年,正从一面混凝土墙上活过来。他一边用极快的语速演唱一首英文rap,一边摆着一个经典的、充满活力的说唱歌手姿势。场景设定在夜晚一个充满都市感的铁路桥下。灯光来自一盏孤零零的街灯,营造出电影般的氛围,充满高能量和惊人的细节。视频的音频部分完全由他的rap构成,没有其他对话或杂音。",
        "video_url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.mp4?Expires=xxx"
    },
    "usage": {
        "duration": 15,
        "input_video_duration": 0,
        "output_video_duration": 15,
        "video_count": 1,
        "SR": 720
    }
}

Task failed

If the task fails, task_status is set to FAILED, and an error code and message are provided. See Error codes to resolve the issue.

{
    "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 queries for 24 hours. After it expires, the result can no longer be queried, and the following error is returned.

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

DashScope SDK

The SDK parameter names are basically the same as those of the HTTP API, and the parameter structure is encapsulated based on the features of each language.

Because image-to-video tasks take a long time (typically 1 to 5 minutes), the SDK encapsulates the HTTP asynchronous invocation process at the underlying layer and supports both synchronous and asynchronous invocation methods.

The actual processing time depends on the number of queued tasks and the service execution status. Please wait patiently when obtaining the result.

Python SDK

ImportantMake sure that the DashScope Python SDK version is not 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. See Install the SDK to update the SDK.

Set region based on the region of the model (pass it in when constructing the Client; the region value varies by region):

Beijing

region="cn-beijing"

Singapore

region="ap-southeast-1"

Replace {WorkspaceId} with your actual workspace ID.

Synchronous call

Request example
# -*- coding: utf-8 -*-
import dashscope
import os
from dashscope.v2 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",
)

media = [
    {
        "type": "first_frame",
        "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png"
    },
    {
        "type": "driving_audio",
        "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/ozwpvi/rap.mp3"
    }
]

def sample_sync_call():
    print('----sync call, please wait a moment----')
    # generate 为一步式调用(提交任务并等待完成),返回已完成的 Job
    # prompt_extend:1.x 默认开启提示词智能改写;2.0 缺省由服务端决定,此处显式开启保持行为一致
    try:
        job = client.videos.generate(
            model="wan2.7-i2v-2026-04-25",
            media=media,
            resolution="720P",
            duration=10,
            watermark=True,
            prompt="一幅都市奇幻艺术的场景。一个充满动感的涂鸦艺术角色。一个由喷漆所画成的少年,正从一面混凝土墙上活过来。他一边用极快的语速演唱一首英文rap,一边摆着一个经典的、充满活力的说唱歌手姿势。场景设定在夜晚一个充满都市感的铁路桥下。灯光来自一盏孤零零的街灯,营造出电影般的氛围,充满高能量和惊人的细节。视频的音频部分完全由rap构成,没有其他对话或杂音。",
            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()
Response example

The video_url is valid for 24 hours. Download the video in a timely manner.

{
    "request_id": "ac5faf37-ddfa-9720-a0c5-xxxxxx",
    "task_id": "b97c6d86-ad73-4bb7-80ff-xxxxxx",
    "status": "SUCCEEDED",
    "video_url": "https://dashscope-a717.oss-accelerate.aliyuncs.com/xxx.mp4?Expires=xxx",
    "task_metrics": {
        "TOTAL": 1,
        "SUCCEEDED": 1,
        "FAILED": 0
    },
    "usage": {
        "video_count": 1,
        "duration": 10,
        "input_video_duration": 0,
        "output_video_duration": 10,
        "SR": 720
    }
}

Asynchronous call

Request example
# -*- coding: utf-8 -*-
import dashscope
import os
from dashscope.v2 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",
)

media = [
    {
        "type": "first_frame",
        "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png"
    },
    {
        "type": "driving_audio",
        "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/ozwpvi/rap.mp3"
    }
]

def sample_async_call():
    # 提交异步任务,立即返回任务信息
    # prompt_extend:1.x 默认开启提示词智能改写;2.0 缺省由服务端决定,此处显式开启保持行为一致
    try:
        job = client.videos.jobs.create(
            model="wan2.7-i2v-2026-04-25",
            media=media,
            resolution="720P",
            duration=10,
            watermark=True,
            prompt="一幅都市奇幻艺术的场景。一个充满动感的涂鸦艺术角色。一个由喷漆所画成的少年,正从一面混凝土墙上活过来。他一边用极快的语速演唱一首英文rap,一边摆着一个经典的、充满活力的说唱歌手姿势。场景设定在夜晚一个充满都市感的铁路桥下。灯光来自一盏孤零零的街灯,营造出电影般的氛围,充满高能量和惊人的细节。视频的音频部分完全由rap构成,没有其他对话或杂音。",
            prompt_extend=True,
        )
        print(job)
        print("task_id: %s" % job.task_id)
    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")
        return

    # 查询任务状态
    try:
        snapshot = client.videos.jobs.fetch(job.task_id)
        print(snapshot.status)
    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")

    # 等待任务完成(指数退避轮询,默认总预算24小时)
    try:
        done = client.videos.jobs.wait(job)
        print(done)
        print(done.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_async_call()
Response example
  1. Response example for creating a task
{
    "request_id": "6dc3bf6c-be18-9268-9c27-xxxxxx",
    "task_id": "686391d9-7ecf-4290-a8e9-xxxxxx",
    "status": "PENDING"
}
  1. Response example for querying the task result

The video_url is valid for 24 hours. Download the video in a timely manner.

{
    "request_id": "ac5faf37-ddfa-9720-a0c5-xxxxxx",
    "task_id": "b97c6d86-ad73-4bb7-80ff-xxxxxx",
    "status": "SUCCEEDED",
    "video_url": "https://dashscope-a717.oss-accelerate.aliyuncs.com/xxx.mp4?Expires=xxx",
    "task_metrics": {
        "TOTAL": 1,
        "SUCCEEDED": 1,
        "FAILED": 0
    },
    "usage": {
        "video_count": 1,
        "duration": 10,
        "input_video_duration": 0,
        "output_video_duration": 10,
        "SR": 720
    }
}

Java SDK

ImportantMake sure that the DashScope Java SDK version is not lower than 2.22.14 before running the following code.

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

Set Constants.baseHttpApiUrl based on the region of the model:

Beijing

Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"

Singapore

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

Replace {WorkspaceId} with your actual workspace ID.

Synchronous call

A synchronous call blocks and waits until the video generation is complete and the result is returned.

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.util.ArrayList;
import java.util.List;

public class Image2Video {

    static {
        // 以下为华北2(北京)地域的URL。请将 {WorkspaceId} 替换为您的百炼业务空间ID,各地域的URL不同。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
    }

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

    public static void syncCall() {
        VideoSynthesis videoSynthesis = new VideoSynthesis();
        final String prompt = "一幅都市奇幻艺术的场景。一个充满动感的涂鸦艺术角色。一个由喷漆所画成的少年,正从一面混凝土墙上活过来。他一边用极快的语速演唱一首英文rap,一边摆着一个经典的、充满活力的说唱歌手姿势。场景设定在夜晚一个充满都市感的铁路桥下。灯光来自一盏孤零零的街灯,营造出电影般的氛围,充满高能量和惊人的细节。视频的音频部分完全由他的rap构成,没有其他对话或杂音。";
        List<VideoSynthesisParam.Media> media = new ArrayList<VideoSynthesisParam.Media>(){{
            add(VideoSynthesisParam.Media.builder()
                    .url("https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png")
                    .type("first_frame")
                    .build());
            add(VideoSynthesisParam.Media.builder()
                    .url("https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/ozwpvi/rap.mp3")
                    .type("driving_audio")
                    .build());
        }};
        VideoSynthesisParam param =
                VideoSynthesisParam.builder()
                        .apiKey(apiKey)
                        .model("wan2.7-i2v-2026-04-25")
                        .prompt(prompt)
                        .media(media)
                        .watermark(true)
                        .duration(10)
                        .resolution("720P")
                        .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();
    }
}

Asynchronous call

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.util.ArrayList;
import java.util.List;

public class Image2Video {

    static {
        // 以下为华北2(北京)地域的URL。请将 {WorkspaceId} 替换为您的百炼业务空间ID,各地域的URL不同。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
    }

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

    public static void asyncCall() {
        VideoSynthesis videoSynthesis = new VideoSynthesis();
        final String prompt = "一幅都市奇幻艺术的场景。一个充满动感的涂鸦艺术角色。一个由喷漆所画成的少年,正从一面混凝土墙上活过来。他一边用极快的语速演唱一首英文rap,一边摆着一个经典的、充满活力的说唱歌手姿势。场景设定在夜晚一个充满都市感的铁路桥下。灯光来自一盏孤零零的街灯,营造出电影般的氛围,充满高能量和惊人的细节。视频的音频部分完全由他的rap构成,没有其他对话或杂音。";
        List<VideoSynthesisParam.Media> media = new ArrayList<VideoSynthesisParam.Media>(){{
            add(VideoSynthesisParam.Media.builder()
                    .url("https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png")
                    .type("first_frame")
                    .build());
            add(VideoSynthesisParam.Media.builder()
                    .url("https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/ozwpvi/rap.mp3")
                    .type("driving_audio")
                    .build());
        }};
        VideoSynthesisParam param =
                VideoSynthesisParam.builder()
                        .apiKey(apiKey)
                        .model("wan2.7-i2v-2026-04-25")
                        .prompt(prompt)
                        .media(media)
                        .watermark(true)
                        .duration(10)
                        .resolution("720P")
                        .build();
        VideoSynthesisResult result = null;
        try {
            System.out.println("---async call, please wait a moment----");
            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()));
    }

    public static void main(String[] args) {
        asyncCall();
    }
}

Error codes

If the model call fails and an error message is returned, see Error codes to resolve the issue.

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 material (first frame image or first video clip), but it is not guaranteed to be exactly equal to the input ratio (for example, exactly 3:4). The actual output may deviate slightly.

The following example uses a first frame image as the input to explain the logic:

  • Why does the deviation occur?
    • Execution logic: The aspect ratio of the input image is used as the baseline reference, combined with the target total pixels of the resolution tier. Because the video width and height must be multiples of 16 (video encoding specification), the system automatically fine-tunes the output to the closest valid resolution.
    • Calculation example: For a 750×1000 first frame image (aspect ratio 3:4 = 0.75) with resolution set to "720P" (target total pixels of about 920,000), the resolution of the actual output video is 816×1104 (aspect ratio ≈ 0.739, total pixels of about 900,000).
  • Practical recommendations:

    • Input control: Use a first frame or first video clip that matches the target ratio as the input.
    • Post-processing: If you have strict aspect ratio requirements, we recommend that you use an editing tool to crop the video or add black bars after the video is generated.

Q: How do I obtain the whitelist of access domain names 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 this download URL, note the following: The underlying storage changes dynamically based on business conditions. To prevent outdated information from affecting access, this topic does not provide a fixed OSS domain name whitelist. If you have security control requirements, contact your account manager to obtain the latest OSS domain name list.