Wan2.7 - video editing API reference

Updated at:

The Wan 2.7 video editing model accepts multimodal inputs (text, images, and videos) for instruction-based editing and style transfer .

Related documents: Guide

Applicability

The model, endpoint URL, and API Key must all belong to the same region. Cross-region calls fail.

  • Select Model: Confirm the region that the model belongs to.
  • Select URL: Select the Endpoint URL for the corresponding region. Both HTTP URLs and DashScope SDK URLs are supported.
  • Configure API Key: Obtain the API Key for the region, and then configure the API Key as an environment variable.

NoteSample code in this topic uses 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

Video editing tasks typically take 1 to 5 minutes. The API uses asynchronous calls with two core steps: Create a task -> Poll for the result.

Step 1: Create a task

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 successfully, use the task_id returned by the API to query the result. The task_id is valid for 24 hours. Do not create the task repeatedly; just poll for the result.

Request parameters

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)

Asynchronous processing configuration parameter. HTTP requests support asynchronous calls only, so it 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.

Example value: wan2.7-videoedit.

input object (Required)

Input parameters, including the prompt.

Properties

prompt string (Optional)

Describes the desired elements and visual features in the generated video.

Both Chinese and English are supported. Each Chinese character or English letter counts as one character. Longer text is automatically truncated.

  • wan2.7-videoedit: up to 5,000 characters.

Example value: Change the character's clothes to a cool, flashy outfit and add the hat from the reference image.

negative_prompt string (Optional)

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

Both Chinese and English are supported. The length cannot exceed 500 characters. Longer text is automatically truncated.

Example value: low resolution, error, worst quality, low quality, disfigured, extra fingers, bad proportions.

media array (Required)

A list of media assets, such as images and videos, used as references for video generation.

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

Properties

type string (Required)

The type of the media asset. Valid values:

  • video: Required. The video to be edited.
  • reference_image: Optional. A reference image.

Asset limits:

  • Only one video is allowed.
  • Maximum four reference images.

url string (Required)

The URL, Base64-encoded data, or Asset Center asset_id of the media asset. Assets include videos and images.

Input video (type=video)

The URL or Asset Center asset_id of the video file to be edited.

Video requirements:

  • Format: MP4, MOV.
  • Duration: 2 to 10 s.
  • Resolution: The width and height range from [240,4096] pixels.
  • Aspect Ratio: 1:8 to 8:1.
  • File Size: No more than 100 MB.

Supported input formats:

  1. Public URL:

  2. Temporary URL:

    • The OSS protocol is supported. You must upload a file to get a temporary URL.
    • Example value: oss://dashscope-instant/xxx/xxx.mp4.
  3. Asset Center asset_id

    • Format: ark_asset_vid_xxxxxx.
    • You can obtain this from the Asset Center. Choose one of URL or asset_id.

Input image (type=reference_image)

The URL, Base64-encoded data, or Asset Center asset_id of the reference image.

Image requirements:

  • Format: JPEG, JPG, PNG (transparent channels are 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 20 MB.

Supported input formats:

  1. Public URL:

  2. Temporary URL:

    • The OSS protocol is supported. You must upload a file to get a temporary URL.
    • Example value: oss://dashscope-instant/xxx/xxx.png.
  3. Base64-encoded string:

    • Data format: data:{MIME_type};base64,{base64_data}.
    • Example value: data:image/png;base64,GDU7MtCZzEbTbmRZ...... (This example is truncated for demonstration purposes).

    Base64-encoded data format

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

    • {base64_data}: The Base64-encoded string of the image file.
    • {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

  4. Asset Center asset_id

    • Format: ark_asset_img_xxxxxx.
    • You can obtain this from the Asset Center. Choose one of URL, Base64, or asset_id.

parameters object (Optional)

Parameters for video processing, such as resolution, duration, intelligent prompt rewriting, and watermarking.

Properties

resolution string (Optional)

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

  • wan2.7-videoedit: Valid values are 720P and 1080P. The default value is 1080P.

ratio string (Optional)

The aspect ratio of the generated video.

Behavior:

  • If you do not specify the ratio parameter, the model generates a video with an aspect ratio similar to that of the input video.
  • If you specify the ratio parameter, the model generates a video with the specified ratio.

Valid values:

  • 16:9
  • 9:16
  • 1:1
  • 4:3
  • 3:4

See the table below for the output video resolution (width × height) for different aspect ratios.

Resolution tier

Aspect ratio

Output video resolution (width*height)

720P

16:9

1280*720

9:16

720*1280

1:1

960*960

4:3

1104*832

3:4

832*1104

1080P

16:9

1920*1080

9:16

1080*1920

1:1

1440*1440

4:3

1648*1248

3:4

1248*1648

duration integer (Optional)

The duration of the generated video, in seconds.

Usage tips: Configure this parameter only when you need to "trim the video". If you want the output video to have the same duration as the input video, you do not need to set it (or pass in the default value 0).

Usage rules:

  • Default behavior: The default value is 0, which means the duration of the input video is used without truncation.
  • Truncation: When a specific duration is passed, the system truncates the original video from 0 seconds to the length specified by duration.
  • Value range: An integer in the range [2, 10].

audio_setting string (Optional)

Video sound settings.

  • auto (Default): The model intelligently determines the audio based on the prompt. If the prompt describes sound, new audio might be generated. Otherwise, the original audio of the input asset might be retained.
  • origin: Forces the retention of the original audio from the input video without regeneration.

prompt_extendboolean (Optional)

Enables intelligent prompt rewriting. When enabled, a large model rewrites the input prompt, significantly improving generation quality for shorter prompts at the cost of increased processing time.

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

watermark boolean (Optional)

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

  • false (default)
  • true

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.

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-videoedit",
    "input": {
        "prompt": "将整个画面转换为黏土风格",
        "media": [
            {
                "type": "video",
                "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260402/ldnfdf/wan2.7-videoedit-style-change.mp4"
            }
        ]
    },
    "parameters": {
        "resolution": "720P",
        "prompt_extend": true,
        "watermark": true
    }
}'
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-videoedit",
    "input": {
        "prompt": "将视频中女孩的衣服替换为图片中的衣服",
        "media": [
            {
                "type": "video",
                "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260403/nlspwm/T2VA_22.mp4"
            },
            {
                "type": "reference_image",
                "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260402/fwjpqf/wan2.7-videoedit-change-clothes.png"
            }
        ]
    },
    "parameters": {
        "resolution": "720P",
        "prompt_extend": true,
        "watermark": true
    }
}'

Response parameters

output object

Contains the task output.

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_idstring

Unique request identifier for tracing and troubleshooting.

codestring

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

messagestring

Detailed error message. Returned only for failed requests. 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.

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

Step 2: Query the result

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 tips: Video generation takes several minutes. We recommend using a polling mechanism with a reasonable query interval (for example, 15 seconds) to obtain the result.
  • Task status transitions: PENDING (Queuing) → RUNNING (Processing) → SUCCEEDED (Success) / FAILED (Failed).
  • Result link: After the task succeeds, a video link is returned, which is valid for 24 hours. We recommend downloading the video immediately after you obtain the link and transferring it to permanent storage (such as Alibaba Cloud OSS).
  • task_id validity: 24 hours. After it expires, the result can no longer be queried, and the API returns the task status UNKNOWN.
  • RPS limits: The default RPS of the query API is 20. For higher-frequency queries or event notifications, we recommend configuring asynchronous task callbacks.
  • More operations: For operations such as querying tasks in batches or canceling tasks, see Managing asynchronous tasks.

Request parameters

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 result

Replace {task_id} with the task_id value 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

Contains the task output.

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.
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 the task again.
  • If the status is UNKNOWN, the task does not exist or its status is unknown, which may occur when the task_id does not exist or the 24-hour validity 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

Task execution time. The format is YYYY-MM-DD HH:mm:ss.SSS.

end_time string

Task completion time. 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 format is MP4 (H.264 encoding).

orig_prompt string

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

codestring

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

messagestring

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

usage object

Output statistics. Only successful results are counted.

Properties

input_video_duration float

The duration of the input video, in seconds.

output_video_duration float

The duration of the output video, in seconds.

duration float

The total video duration, used for billing.

Billing formula: duration=input_video_duration+output_video_duration.

SR integer

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

video_count integer

The number of generated videos. Fixed at 1.

request_idstring

Unique request identifier for tracing and troubleshooting.

Task executed successfully

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": "f16ae7e9-d518-92f8-a02c-xxxxxx",
    "output": {
        "task_id": "05e68c7e-850c-49e4-b866-xxxxxx",
        "task_status": "SUCCEEDED",
        "submit_time": "2026-04-03 00:08:03.576",
        "scheduled_time": "2026-04-03 00:08:13.408",
        "end_time": "2026-04-03 00:11:57.286",
        "orig_prompt": "将视频中女孩的衣服替换为图片中的衣服",
        "video_url": "https://dashscope-a717.oss-accelerate.aliyuncs.com/xxx.mp4?xxxx"
    },
    "usage": {
        "duration": 10.04,
        "input_video_duration": 5.02,
        "output_video_duration": 5.02,
        "video_count": 1,
        "SR": 720
    }
}

Task execution failed

If the task execution fails, task_status is set to FAILED, and an error code and message are 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

The task_id query validity is 24 hours. After it expires, the result can no longer be queried, 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"
    }
}

Call via DashScope SDK

The SDK parameter naming is basically the same as that of the HTTP interface, and the parameter structure is encapsulated based on language characteristics.

Since video editing tasks take a long time to complete (usually 1 to 5 minutes), the SDK encapsulates the HTTP asynchronous call process at the underlying layer and supports both synchronous and asynchronous calling methods.

The specific duration depends on the number of queued tasks and service execution status. Please wait patiently when obtaining the result.

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 low, errors such as "url error, please check url!" may occur. Refer to Install the SDK for update instructions.

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

Beijing

region="cn-beijing"

Singapore

region="ap-southeast-1"

Replace {WorkspaceId} with your actual workspace ID.

Synchronous Call

Request example
import base64
import mimetypes
import dashscope
import os
from dashscope import DashScopeError

# 以下为华北2(北京)地域的配置,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的region取值不同。
client = dashscope.Client(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
    # 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)

# 格式为 data:{MIME_type};base64,{base64_data}
def encode_file(file_path):
    mime_type, _ = mimetypes.guess_type(file_path)
    if not mime_type or not mime_type.startswith("image/"):
        raise ValueError("不支持或无法识别的图像格式")
    with open(file_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
    return f"data:{mime_type};base64,{encoded_string}"

# 参考图像URL,支持以下三种输入方式

# 【方式一】使用公网图片URL
reference_image_url = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260402/fwjpqf/wan2.7-videoedit-change-clothes.png"

# 【方式二】使用本地文件(支持绝对路径和相对路径)
# 格式要求:file:// + 文件路径
# 示例(绝对路径):
# reference_image_url = "file://" + "/path/to/image.png"     # Linux/macOS
# reference_image_url = "file://" + "C:/path/to/image.png"    # Windows
# 示例(相对路径):
# reference_image_url = "file://" + "./image.png"             # 相对当前执行文件的路径

# 【方式三】使用Base64编码
# reference_image_url = encode_file("/path/to/image.png")

def sample_sync_call_videoedit():
    # generate 为一步式调用(提交任务并等待完成),返回已完成的 Job
    print('please wait...')
    try:
        job = client.videos.generate(
            model='wan2.7-videoedit',
            prompt='将视频中女孩的衣服替换为图片中的衣服',
            media=[
                {
                    "type": "video",
                    "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260403/nlspwm/T2VA_22.mp4"
                },
                {
                    "type": "reference_image",
                    "url": reference_image_url
                }
            ],
            resolution='720P',
            prompt_extend=True,
            watermark=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_videoedit()
Response example

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

{
    "request_id": "d6c3c865-34e9-98a9-a53d-xxxxxx",
    "task_id": "1de7c853-755a-454a-91bc-xxxxxx",
    "status": "SUCCEEDED",
    "video_url": "https://dashscope-a717.oss-accelerate.aliyuncs.com/xxx.mp4?Expires=xxxx",
    "task_metrics": {
        "TOTAL": 1,
        "SUCCEEDED": 1,
        "FAILED": 0
    },
    "usage": {
        "video_count": 1,
        "duration": 10.08,
        "input_video_duration": 5.04,
        "output_video_duration": 5.04,
        "SR": 720
    }
}

Asynchronous Call

Request example
import base64
import mimetypes
import dashscope
import os
from dashscope import DashScopeError

# 以下为华北2(北京)地域的配置,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的region取值不同。
client = dashscope.Client(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
    # 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)

# 格式为 data:{MIME_type};base64,{base64_data}
def encode_file(file_path):
    mime_type, _ = mimetypes.guess_type(file_path)
    if not mime_type or not mime_type.startswith("image/"):
        raise ValueError("不支持或无法识别的图像格式")
    with open(file_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
    return f"data:{mime_type};base64,{encoded_string}"

# 参考图像URL,支持以下三种输入方式

# 【方式一】使用公网图片URL
reference_image_url = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260402/fwjpqf/wan2.7-videoedit-change-clothes.png"

# 【方式二】使用本地文件(支持绝对路径和相对路径)
# 格式要求:file:// + 文件路径
# 示例(绝对路径):
# reference_image_url = "file://" + "/path/to/image.png"     # Linux/macOS
# reference_image_url = "file://" + "C:/path/to/image.png"    # Windows
# 示例(相对路径):
# reference_image_url = "file://" + "./image.png"             # 相对当前执行文件的路径

# 【方式三】使用Base64编码
# reference_image_url = encode_file("/path/to/image.png")

def sample_async_call_videoedit():
    # call async api, will return the task information
    # you can get task status with the returned task id.
    try:
        job = client.videos.jobs.create(
            model='wan2.7-videoedit',
            prompt='将视频中女孩的衣服替换为图片中的衣服',
            media=[
                {
                    "type": "video",
                    "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260403/nlspwm/T2VA_22.mp4"
                },
                {
                    "type": "reference_image",
                    "url": reference_image_url
                }
            ],
            resolution='720P',
            prompt_extend=True,
            watermark=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

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

    # wait the task complete, will call fetch interval, and check it's in finished status.
    # (2.0 jobs.wait 指数退避轮询,默认总预算24小时,任务 FAILED 会抛出异常)
    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_videoedit()
Response example
  1. Response example of creating a task
{
    "request_id": "f16ae7e9-d518-92f8-a02c-xxxxxx",
    "task_id": "05e68c7e-850c-49e4-b866-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": "d6c3c865-34e9-98a9-a53d-xxxxxx",
    "task_id": "1de7c853-755a-454a-91bc-xxxxxx",
    "status": "SUCCEEDED",
    "video_url": "https://dashscope-a717.oss-accelerate.aliyuncs.com/xxx.mp4?Expires=xxxx",
    "task_metrics": {
        "TOTAL": 1,
        "SUCCEEDED": 1,
        "FAILED": 0
    },
    "usage": {
        "video_count": 1,
        "duration": 10.08,
        "input_video_duration": 5.04,
        "output_video_duration": 5.04,
        "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 low, errors such as "url error, please check url!" may occur. Refer to Install the SDK for update instructions.

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

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.JsonUtils;
import com.alibaba.dashscope.utils.Constants;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

public class VideoEdit {

    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
    public static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // 参考图像URL,支持以下三种输入方式

    // 【方式一】使用公网图片URL
    static String referenceImageUrl = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260402/fwjpqf/wan2.7-videoedit-change-clothes.png";

    // 【方式二】使用本地文件(支持绝对路径和相对路径)
    // 格式要求:file:// + 文件路径
    // 示例(绝对路径):
    // static String referenceImageUrl = "file://" + "/path/to/image.png";     // Linux/macOS
    // static String referenceImageUrl = "file://" + "C:/path/to/image.png";   // Windows
    // 示例(相对路径):
    // static String referenceImageUrl = "file://" + "./image.png";             // 相对当前执行文件的路径

    // 【方式三】使用Base64编码
    // static String referenceImageUrl = encodeFile("/path/to/image.png");

    // 格式为 data:{MIME_type};base64,{base64_data}
    public static String encodeFile(String filePath) {
        Path path = Paths.get(filePath);
        if (!Files.exists(path)) {
            throw new IllegalArgumentException("文件不存在: " + filePath);
        }
        String mimeType = null;
        try {
            mimeType = Files.probeContentType(path);
        } catch (IOException e) {
            throw new IllegalArgumentException("无法检测文件类型: " + filePath);
        }
        if (mimeType == null || !mimeType.startsWith("image/")) {
            throw new IllegalArgumentException("不支持或无法识别的图像格式");
        }
        byte[] fileBytes = null;
        try {
            fileBytes = Files.readAllBytes(path);
        } catch (IOException e) {
            throw new IllegalArgumentException("无法读取文件内容: " + filePath);
        }
        String encodedString = Base64.getEncoder().encodeToString(fileBytes);
        return "data:" + mimeType + ";base64," + encodedString;
    }

    public static void videoEdit() throws ApiException, NoApiKeyException, InputRequiredException {
        VideoSynthesis vs = new VideoSynthesis();
        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/20260403/nlspwm/T2VA_22.mp4")
                    .type("video")
                    .build());
            add(VideoSynthesisParam.Media.builder()
                    .url(referenceImageUrl)
                    .type("reference_image")
                    .build());
        }};
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("resolution", "720P");
        parameters.put("prompt_extend", true);
        parameters.put("watermark", true);

        VideoSynthesisParam param =
                VideoSynthesisParam.builder()
                        .apiKey(apiKey)
                        .model("wan2.7-videoedit")
                        .prompt("将视频中女孩的衣服替换为图片中的衣服")
                        .media(media)
                        .parameters(parameters)
                        .build();
        System.out.println("please wait...");
        VideoSynthesisResult result = vs.call(param);
        System.out.println(JsonUtils.toJson(result));
    }

    public static void main(String[] args) {
        try {
            videoEdit();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}
Response example

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

{
    "request_id": "0a15ad3c-cde7-9f7e-b8d2-xxxxxx",
    "output": {
        "task_id": "0025d1e1-009a-4f53-9c27-xxxxx",
        "task_status": "SUCCEEDED",
        "video_url": "https://dashscope-a717.oss-accelerate.aliyuncs.com/xxx.mp4?Expires=xxx",
        "orig_prompt": "将视频中女孩的衣服替换为图片中的衣服",
        "submit_time": "2026-04-10 17:21:01.719",
        "scheduled_time": "2026-04-10 17:21:13.182",
        "end_time": "2026-04-10 17:31:41.286"
    },
    "usage": {
        "video_count": 1,
        "duration": 10.08,
        "input_video_duration": 5.04,
        "output_video_duration": 5.04,
        "SR": "720"
    },
    "status_code": 200,
    "code": "",
    "message": ""
}

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.aigc.videosynthesis.VideoSynthesisListResult;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

public class VideoEdit {

    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
    public static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // 参考图像URL,支持以下三种输入方式

    // 【方式一】使用公网图片URL
    static String referenceImageUrl = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260402/fwjpqf/wan2.7-videoedit-change-clothes.png";

    // 【方式二】使用本地文件(支持绝对路径和相对路径)
    // 格式要求:file:// + 文件路径
    // 示例(绝对路径):
    // static String referenceImageUrl = "file://" + "/path/to/image.png";     // Linux/macOS
    // static String referenceImageUrl = "file://" + "C:/path/to/image.png";   // Windows
    // 示例(相对路径):
    // static String referenceImageUrl = "file://" + "./image.png";             // 相对当前执行文件的路径

    // 【方式三】使用Base64编码
    // static String referenceImageUrl = encodeFile("/path/to/image.png");

    // 格式为 data:{MIME_type};base64,{base64_data}
    public static String encodeFile(String filePath) {
        Path path = Paths.get(filePath);
        if (!Files.exists(path)) {
            throw new IllegalArgumentException("文件不存在: " + filePath);
        }
        String mimeType = null;
        try {
            mimeType = Files.probeContentType(path);
        } catch (IOException e) {
            throw new IllegalArgumentException("无法检测文件类型: " + filePath);
        }
        if (mimeType == null || !mimeType.startsWith("image/")) {
            throw new IllegalArgumentException("不支持或无法识别的图像格式");
        }
        byte[] fileBytes = null;
        try {
            fileBytes = Files.readAllBytes(path);
        } catch (IOException e) {
            throw new IllegalArgumentException("无法读取文件内容: " + filePath);
        }
        String encodedString = Base64.getEncoder().encodeToString(fileBytes);
        return "data:" + mimeType + ";base64," + encodedString;
    }

    public static void videoEdit() throws ApiException, NoApiKeyException, InputRequiredException {
        VideoSynthesis vs = new VideoSynthesis();
        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/20260403/nlspwm/T2VA_22.mp4")
                    .type("video")
                    .build());
            add(VideoSynthesisParam.Media.builder()
                    .url(referenceImageUrl)
                    .type("reference_image")
                    .build());
        }};
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("resolution", "720P");
        parameters.put("prompt_extend", true);
        parameters.put("watermark", true);

        VideoSynthesisParam param =
                VideoSynthesisParam.builder()
                        .apiKey(apiKey)
                        .model("wan2.7-videoedit")
                        .prompt("将视频中女孩的衣服替换为图片中的衣服")
                        .media(media)
                        .parameters(parameters)
                        .build();

        // 异步调用
        VideoSynthesisResult task = vs.asyncCall(param);
        System.out.println(JsonUtils.toJson(task));
        System.out.println("please wait...");

        // 获取结果
        VideoSynthesisResult result = vs.wait(task, apiKey);
        System.out.println(JsonUtils.toJson(result));
    }

    // 获取任务列表
    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);
    }

    // 获取单个任务结果
    public static void fetchTask(String taskId) throws ApiException, NoApiKeyException {
        VideoSynthesis is = new VideoSynthesis();
        // 如果已设置 DASHSCOPE_API_KEY 为环境变量,apiKey 可为空
        VideoSynthesisResult result = is.fetch(taskId, apiKey);
        System.out.println(result.getOutput());
        System.out.println(result.getUsage());
    }

    public static void main(String[] args) {
        try {
            videoEdit();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}
Response example
  1. Response example of creating a task
{
    "request_id": "f16ae7e9-d518-92f8-a02c-xxxxxx",
    "output": {
        "task_id": "05e68c7e-850c-49e4-b866-xxxxxx",
        "task_status": "PENDING",
        "video_url": ""
    },
    "usage": null,
    "status_code": 200,
    "code": "",
    "message": ""
}
  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": "0a15ad3c-cde7-9f7e-b8d2-xxxxxx",
    "output": {
        "task_id": "0025d1e1-009a-4f53-9c27-xxxxx",
        "task_status": "SUCCEEDED",
        "video_url": "https://dashscope-a717.oss-accelerate.aliyuncs.com/xxx.mp4?Expires=xxx",
        "orig_prompt": "将视频中女孩的衣服替换为图片中的衣服",
        "submit_time": "2026-04-10 17:21:01.719",
        "scheduled_time": "2026-04-10 17:21:13.182",
        "end_time": "2026-04-10 17:31:41.286"
    },
    "usage": {
        "video_count": 1,
        "duration": 10.08,
        "input_video_duration": 5.04,
        "output_video_duration": 5.04,
        "SR": "720"
    },
    "status_code": 200,
    "code": "",
    "message": ""
}

Error codes

If a model call fails, refer to Error codes for troubleshooting.