All Products
Search
Document Center

Alibaba Cloud Model Studio:Wan2.7-I2V API reference

Last Updated:Nov 24, 2026

The Wan2.7-I2V model is fully upgraded. It supports multimodal input (text/image/audio/video) and can complete three major tasks: first-frame-to-video, first-and-last-frame-to-video, and video continuation.

Related documents: User Guide

NoteThe newly launched I2V API (wan2.7 model) supports the preceding three tasks and is recommended as the first choice.

The original I2V based on first frame (wan2.6 and earlier models) only supports first-frame-to-video.

Scope

To ensure successful calls, make sure that the model, endpoint URL, and API Key belong to the same region. Cross-region calls will fail.

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

ImportantAlibaba Cloud Model Studio provides workspace-specific domains for the China (Beijing) and Singapore regions. These domains deliver superior performance and higher stability for inference requests. We recommend that you migrate 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

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

HTTP calls

ImportantThis API uses the new I2V protocol and supports only the wan2.7 model.

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

Step 1: Create a task to obtain the task ID

Singapore

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

Beijing

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

When you call the API, 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. Poll for the result instead.
  • For getting started, see Postman.

Request parameters

Content-Typestring(required)

The request content type. You must set this parameter to application/json.

Authorizationstring(required)

Request authentication. This API uses the Alibaba Cloud Model Studio API Key for authentication. Example value: Bearer sk-xxxx.

X-DashScope-Asyncstring(required)

Asynchronous processing configuration parameter. HTTP requests only support asynchronous calls, and this parameter must be set to enable.

ImportantIf 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. For the model list and prices, see Model pricing.

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

input object (Required)

The basic input information, such as the prompt.

Properties

prompt string (Optional)

The text prompt. It describes the elements and visual features that you want to include in the generated video.

Both Chinese and English are supported, with a maximum length of 5,000 characters. Each Chinese character or letter counts as one character, and any excess is automatically truncated.

Example value: A kitten running on the grass.

For tips on how to use prompts, see T2V/I2V prompt guide.

negative_prompt string (Optional)

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

Both Chinese and English are supported, with a maximum length of 500 characters; any excess is automatically truncated.

Example value: low resolution, fault, worst quality, low quality, mutilated, extra fingers, bad proportions, etc.

media array (Required)

The list of media assets, used to specify the reference materials (images, audio, and videos) required for video generation.

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

Media asset combinations

Only the following specific media asset combinations are supported; invalid combinations will return an error.

  • First frame to video:

    • First frame: first_frame
    • First frame + audio: first_frame+driving_audio
  • First and last frames to video:

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

Limits: Each type can appear at most once in the media array (for example, you cannot pass in two first_frame at the same time).

url string (Required)

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

Input image (type=first_frame or last_frame)

The URL of the first frame or last frame, or Base64-encoded data. Currently, first-frame-to-video and first-and-last-frame-to-video are supported.

Image limits:

  • Format: JPEG, JPG, PNG (transparent channels not supported), BMP, WEBP.
  • Resolution: The width and height range from [240, 8000] pixels.
  • Aspect ratio: 1:8 to 8:1.
  • File size: no more than 20MB.

Supported input formats:

  1. Public URL:

  2. String of the Base64-encoded image:

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

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

      Base64-encoded data format

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

      • {base64_data}: the string of the image file after Base64 encoding.
      • {MIME_type}: the media type of the image, which must match the file format.

      Image format

      MIME Type

      JPEG

      image/jpeg

      JPG

      image/jpeg

      PNG

      image/png

      BMP

      image/bmp

      WEBP

      image/webp

Input audio (type=driving_audio)

The URL of the audio file.

  • If audio is provided: the model uses the audio as the driving source to generate the video (for example, lip sync and beat-synchronized movements).
  • If no audio is provided: the model automatically generates matching background music or sound effects based on the video content.

Audio limits:

  • Format: wav, mp3.
  • Duration: 2 to 30s.
  • File size: no more than 15MB.
  • 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 length is shorter than the video duration, the portion beyond the audio length is silent video. 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:

Input video (type=first_clip)

The URL of the video file. The model continues generating video content based on the input video, and 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 has a total duration of 15 seconds, billed at 15 seconds.

Video limits:

  • Format: mp4, mov.
  • Duration: 2 to 10s.
  • Resolution: The width and height range from [240, 4096] pixels.
  • Aspect ratio: 1:8 to 8:1.
  • File size: no more than 100MB.

Supported input formats:

  1. Public URL:

parameters object (Optional)

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

Properties

resolution string (Optional)

ImportantThe resolution directly affects the fee. Confirm the model price before you call the API.

The resolution tier of the generated video, used to control the video clarity (total pixels).

Based on the selected resolution tier, the model automatically scales to a similar total pixel count. The video aspect ratio should be kept consistent with the input asset (first frame or first video segment) whenever possible. For more information, see FAQ.

Valid values:

  • 720P
  • 1080P (default value)

duration integer (Optional)

ImportantThe duration directly affects the fee, which is billed per second. Confirm the model price before you call the API.

The duration of the generated video, in seconds.

An integer between [2, 15]. The default value is 5.

prompt_extendboolean (Optional)

Whether to enable intelligent prompt rewriting. When enabled, a large model is used to intelligently rewrite the input prompt. This significantly improves the generation results for short prompts but increases the processing time.

  • true: default value, intelligent rewriting enabled.
  • false: intelligent rewriting disabled.

watermark boolean (Optional)

Whether to add a watermark. The watermark is located in the lower-right corner of the video, with fixed text "AI-generated".

  • false: default value, no watermark added.
  • true: watermark added.

seedinteger (Optional)

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

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

Note that model generation is probabilistic. Even with the same seed, identical generation results cannot be guaranteed.

First frame to video

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


# Singapore region. 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/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
    }
}'

First and last frame to video

Generate a video by providing the first frame and last frame.


# Singapore region. 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/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

Based on the first video segment, the model generates the subsequent content.


# Singapore region. 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/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

Task ID. The validity period for queries is 24 hours.

task_status string

Task status.

Enumerated value

  • PENDING: Task queuing
  • RUNNING: Task processing
  • SUCCEEDED: Task executed successfully
  • FAILED: Task execution failed
  • CANCELED: Task canceled
  • UNKNOWN: Task does not exist or status unknown

request_idstring

The unique request identifier. It can be used for tracing request details 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 information returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.

Success response

Save the task_id for querying 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. For troubleshooting, see Error codes.

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

Step 2: Query the result by task ID

Singapore

GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}

Beijing

GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}

When you call the API, replace {WorkspaceId} with your actual workspace ID.

Note

  • 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 result.
  • Task status transition: PENDING (Queuing) → RUNNING (Processing) → SUCCEEDED (Success) / FAILED (Failed).
  • Result link: After the task succeeds, a video link is returned, valid for 24 hours. We recommend downloading the video immediately after obtaining the link and storing it in 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.

Request parameters

Request headers

Authorizationstring(required)

Request authentication. This API uses the Alibaba Cloud Model Studio API Key for authentication. Example value: Bearer sk-xxxx.

URL path parameters

task_id string (Required)

The task ID.

Query the task result

Replace {task_id} entirely with the task_id value returned by the API in the previous step. The task_id is valid for queries for 24 hours. Also replace {WorkspaceId} with your actual Workspace ID.

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

Response parameters

outputobject

Task output information.

Properties

task_id string

Task ID. The validity period for queries is 24 hours.

task_status string

Task status.

Enumerated value

  • PENDING: Task queuing
  • RUNNING: Task processing
  • SUCCEEDED: Task executed successfully
  • FAILED: Task execution failed
  • CANCELED: Task canceled
  • UNKNOWN: Task does not exist or status unknown
Status transitions during polling:
  • PENDING (Queuing) → RUNNING (Processing) → SUCCEEDED (Success) / FAILED (Failed).
  • The status on 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 a new task.
  • If the status is UNKNOWN, the task does not exist or the 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 task submission time. The time zone is UTC+8, in the format YYYY-MM-DD HH:mm:ss.SSS.

scheduled_time string

The task execution time. The time zone is UTC+8, in the format YYYY-MM-DD HH:mm:ss.SSS.

end_time string

The task completion time. The time zone is UTC+8, in the format 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 via this URL. The video format is MP4 (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 information returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.

usage object

Output information 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

Total video duration, used for billing.

SR integer

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

video_count integer

The number of output videos. Fixed to 1.

request_idstring

The unique request identifier. It can be used for tracing request details and troubleshooting.

Task executed successfully

The video URL is retained for only 24 hours and will be automatically deleted 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 execution failed

If the task fails, task_status will be set to FAILED, and an error code and message will be provided. See error codes for troubleshooting.

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

task_id can be queried within 24 hours. After that, queries are no longer available and the following error message is returned.

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

DashScope SDK calls

The SDK parameter naming is basically consistent with the HTTP API, and the parameter structure is encapsulated based on language characteristics.

I2V tasks take a long time (usually 1 to 5 minutes), so the SDK encapsulates the HTTP asynchronous call process at the underlying layer and supports both synchronous and asynchronous calls.

The actual time required depends on the number of queued tasks and service execution status. Please be patient when retrieving results.

Python SDK calls

ImportantMake sure the DashScope Python SDK version is no earlier 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 based on the region where the model is located (pass it in when constructing the Client; the region value varies by region):

Singapore

region="ap-southeast-1"

Beijing

region="cn-beijing"

When you call the API, replace {WorkspaceId} with your actual workspace ID.

Synchronous Call

Request example
# -*- coding: utf-8 -*-
import dashscope
import os
from dashscope import DashScopeError

# The following configuration is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. The region value varies by region.
client = dashscope.Client(
    # If the environment variable is not configured, set your Model Studio API key directly: api_key="sk-xxx"
    # API keys are region-specific. 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",
)

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 is a one-step call (submit the task and wait for completion) and returns a completed Job
    # prompt_extend: in 1.x, prompt smart rewriting is enabled by default; in 2.0 it is decided by the server by default. It is explicitly enabled here to keep the behavior consistent
    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 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()
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 import DashScopeError

# The following configuration is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. The region value varies by region.
client = dashscope.Client(
    # If the environment variable is not configured, set your Model Studio API key directly: api_key="sk-xxx"
    # API keys are region-specific. 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",
)

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():
    # Submit the asynchronous task and return the task information immediately
    # prompt_extend: in 1.x, prompt smart rewriting is enabled by default; in 2.0 it is decided by the server by default. It is explicitly enabled here to keep the behavior consistent
    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 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")
        return

    # Query the task status
    try:
        snapshot = client.videos.jobs.fetch(job.task_id)
        print(snapshot.status)
    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")

    # Wait for the task to complete (exponential backoff polling, default total budget of 24 hours)
    try:
        done = client.videos.jobs.wait(job)
        print(done)
        print(done.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_async_call()
Response example
  1. Response example of creating a task
{
    "request_id": "6dc3bf6c-be18-9268-9c27-xxxxxx",
    "task_id": "686391d9-7ecf-4290-a8e9-xxxxxx",
    "status": "PENDING"
}
  1. Response example of 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 calls

ImportantMake sure the DashScope Java SDK version is no earlier 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. Refer to Install SDK to update it.

Set Constants.baseHttpApiUrl based on the region where the model is located:

Singapore

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

Beijing

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

When you call the API, replace {WorkspaceId} with your actual workspace ID.

Synchronous Call

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

Request example

Asynchronous Call

Request example

Error codes

If the model call fails and returns an error message, 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 cannot be guaranteed to be strictly equal to the input ratio (for example, exactly 3:4). The actual output may have slight deviations.

The following uses "inputting a first frame image" as an example to explain the specific logic:

  • Why is there a deviation?
    • Execution logic: The system uses the input image ratio as the baseline ratio reference, combines it with the target total pixels of the resolution tier, and the video width and height must be multiples of 16 (video encoding specification), so the system automatically fine-tunes to the nearest valid resolution.
    • Calculation example: Input a first frame image of 750×1000 (aspect ratio 3:4 = 0.75) and set resolution = "720P" (target total pixels of approximately 920,000). The actual output video resolution is 816×1104 (aspect ratio ≈ 0.739, total pixels of approximately 900,000).
  • Best practices:

    • Input control: Use a first frame or first video clip that matches the target ratio as the input whenever possible.
    • Post-processing: If you have strict ratio requirements, after the video is generated, use an editing tool to perform simple cropping or black-bar padding.

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 firewall whitelist rules for this download URL, note that because the underlying storage changes dynamically based on business conditions, this document 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.