curl --request GET \
--url 'https://toapis.com/v1/videos/generations/task_01K9S419324DREZFBWNSVXYR6H' \
--header 'Authorization: Bearer <token>'
import requests
import time
API_BASE = 'https://toapis.com'
API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx'
headers = {
'Authorization': f'Bearer {API_KEY}'
}
def get_video_status(task_id):
response = requests.get(f'{API_BASE}/v1/videos/generations/{task_id}', headers=headers)
return response.json()
def wait_for_video(task_id, max_attempts=60, interval=10):
for _ in range(max_attempts):
result = get_video_status(task_id)
status = result.get('status')
progress = result.get('progress', 0)
print(f"狀態: {status}, 進度: {progress}%")
if status == 'completed':
return result
elif status == 'failed':
raise Exception(f"任務失敗: {result}")
time.sleep(interval)
raise Exception("任務超時")
# 使用示例
task_id = "video_7497f4d5-3a88-44c7-923a-967fa7d941a0"
result = wait_for_video(task_id)
print(f"視頻URL: {result['result']['data'][0]['url']}")
const API_BASE = 'https://toapis.com';
const API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx';
async function getVideoStatus(taskId) {
const response = await fetch(`${API_BASE}/v1/videos/generations/${taskId}`, {
headers: {
'Authorization': `Bearer ${API_KEY}`
}
});
return response.json();
}
async function waitForVideo(taskId, maxAttempts = 60, interval = 10000) {
for (let i = 0; i < maxAttempts; i++) {
const result = await getVideoStatus(taskId);
const status = result.status;
const progress = result.progress || 0;
console.log(`狀態: ${status}, 進度: ${progress}%`);
if (status === 'completed') {
return result;
} else if (status === 'failed') {
throw new Error(`任務失敗: ${JSON.stringify(result)}`);
}
await new Promise(r => setTimeout(r, interval));
}
throw new Error('任務超時');
}
// 使用示例
const taskId = 'video_7497f4d5-3a88-44c7-923a-967fa7d941a0';
waitForVideo(taskId).then(result => {
console.log('視頻URL:', result.result.data[0].url);
console.log('格式:', result.result.data[0].format);
});
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
func getVideoStatus(taskId string) (map[string]interface{}, error) {
url := fmt.Sprintf("https://toapis.com/v1/videos/generations/%s", taskId)
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("Authorization", "Bearer <token>")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
return result, nil
}
func main() {
taskId := "video_7497f4d5-3a88-44c7-923a-967fa7d941a0"
for i := 0; i < 60; i++ {
result, _ := getVideoStatus(taskId)
status := result["status"].(string)
progress := int(result["progress"].(float64))
fmt.Printf("狀態: %s, 進度: %d%%\n", status, progress)
if status == "completed" {
fmt.Println("視頻生成完成!")
resultData := result["result"].(map[string]interface{})
dataArray := resultData["data"].([]interface{})
videoData := dataArray[0].(map[string]interface{})
fmt.Println("視頻URL:", videoData["url"])
break
}
time.Sleep(10 * time.Second)
}
}
{
"id": "video_7497f4d5-3a88-44c7-923a-967fa7d941a0",
"object": "generation.task",
"model": "sora-2",
"status": "queued",
"progress": 0,
"created_at": 1768380222
}
{
"id": "video_7497f4d5-3a88-44c7-923a-967fa7d941a0",
"object": "generation.task",
"model": "sora-2",
"status": "in_progress",
"progress": 65,
"created_at": 1768380222
}
{
"id": "video_7497f4d5-3a88-44c7-923a-967fa7d941a0",
"client_business_id": "order_20260428_001",
"object": "generation.task",
"model": "sora-2",
"status": "completed",
"progress": 100,
"created_at": 1768380222,
"completed_at": 1768380514,
"expires_at": 1768466914,
"result": {
"type": "video",
"data": [
{
"url": "https://files.toapis.com/sora/7712af45-ca35-4a15-b800-f20ea623665b.mp4",
"format": "mp4"
}
]
}
}
{
"id": "video_7497f4d5-3a88-44c7-923a-967fa7d941a0",
"object": "generation.task",
"model": "sora-2",
"status": "failed",
"progress": 0,
"created_at": 1768380222,
"error": {
"code": "generation_failed",
"message": "生成失敗: 內容違反了內容政策"
}
}
{
"error": {
"code": 404,
"message": "任務不存在",
"type": "not_found_error"
}
}
{
"error": {
"code": 401,
"message": "身份驗證失敗,請檢查您的API密鑰",
"type": "authentication_error"
}
}
獲取視頻任務狀態
獲取視頻任務狀態
查詢視頻生成任務的狀態和結果
GET
/
v1
/
videos
/
generations
/
{task_id}
curl --request GET \
--url 'https://toapis.com/v1/videos/generations/task_01K9S419324DREZFBWNSVXYR6H' \
--header 'Authorization: Bearer <token>'
import requests
import time
API_BASE = 'https://toapis.com'
API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx'
headers = {
'Authorization': f'Bearer {API_KEY}'
}
def get_video_status(task_id):
response = requests.get(f'{API_BASE}/v1/videos/generations/{task_id}', headers=headers)
return response.json()
def wait_for_video(task_id, max_attempts=60, interval=10):
for _ in range(max_attempts):
result = get_video_status(task_id)
status = result.get('status')
progress = result.get('progress', 0)
print(f"狀態: {status}, 進度: {progress}%")
if status == 'completed':
return result
elif status == 'failed':
raise Exception(f"任務失敗: {result}")
time.sleep(interval)
raise Exception("任務超時")
# 使用示例
task_id = "video_7497f4d5-3a88-44c7-923a-967fa7d941a0"
result = wait_for_video(task_id)
print(f"視頻URL: {result['result']['data'][0]['url']}")
const API_BASE = 'https://toapis.com';
const API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx';
async function getVideoStatus(taskId) {
const response = await fetch(`${API_BASE}/v1/videos/generations/${taskId}`, {
headers: {
'Authorization': `Bearer ${API_KEY}`
}
});
return response.json();
}
async function waitForVideo(taskId, maxAttempts = 60, interval = 10000) {
for (let i = 0; i < maxAttempts; i++) {
const result = await getVideoStatus(taskId);
const status = result.status;
const progress = result.progress || 0;
console.log(`狀態: ${status}, 進度: ${progress}%`);
if (status === 'completed') {
return result;
} else if (status === 'failed') {
throw new Error(`任務失敗: ${JSON.stringify(result)}`);
}
await new Promise(r => setTimeout(r, interval));
}
throw new Error('任務超時');
}
// 使用示例
const taskId = 'video_7497f4d5-3a88-44c7-923a-967fa7d941a0';
waitForVideo(taskId).then(result => {
console.log('視頻URL:', result.result.data[0].url);
console.log('格式:', result.result.data[0].format);
});
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
func getVideoStatus(taskId string) (map[string]interface{}, error) {
url := fmt.Sprintf("https://toapis.com/v1/videos/generations/%s", taskId)
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("Authorization", "Bearer <token>")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
return result, nil
}
func main() {
taskId := "video_7497f4d5-3a88-44c7-923a-967fa7d941a0"
for i := 0; i < 60; i++ {
result, _ := getVideoStatus(taskId)
status := result["status"].(string)
progress := int(result["progress"].(float64))
fmt.Printf("狀態: %s, 進度: %d%%\n", status, progress)
if status == "completed" {
fmt.Println("視頻生成完成!")
resultData := result["result"].(map[string]interface{})
dataArray := resultData["data"].([]interface{})
videoData := dataArray[0].(map[string]interface{})
fmt.Println("視頻URL:", videoData["url"])
break
}
time.Sleep(10 * time.Second)
}
}
{
"id": "video_7497f4d5-3a88-44c7-923a-967fa7d941a0",
"object": "generation.task",
"model": "sora-2",
"status": "queued",
"progress": 0,
"created_at": 1768380222
}
{
"id": "video_7497f4d5-3a88-44c7-923a-967fa7d941a0",
"object": "generation.task",
"model": "sora-2",
"status": "in_progress",
"progress": 65,
"created_at": 1768380222
}
{
"id": "video_7497f4d5-3a88-44c7-923a-967fa7d941a0",
"client_business_id": "order_20260428_001",
"object": "generation.task",
"model": "sora-2",
"status": "completed",
"progress": 100,
"created_at": 1768380222,
"completed_at": 1768380514,
"expires_at": 1768466914,
"result": {
"type": "video",
"data": [
{
"url": "https://files.toapis.com/sora/7712af45-ca35-4a15-b800-f20ea623665b.mp4",
"format": "mp4"
}
]
}
}
{
"id": "video_7497f4d5-3a88-44c7-923a-967fa7d941a0",
"object": "generation.task",
"model": "sora-2",
"status": "failed",
"progress": 0,
"created_at": 1768380222,
"error": {
"code": "generation_failed",
"message": "生成失敗: 內容違反了內容政策"
}
}
{
"error": {
"code": 404,
"message": "任務不存在",
"type": "not_found_error"
}
}
{
"error": {
"code": 401,
"message": "身份驗證失敗,請檢查您的API密鑰",
"type": "authentication_error"
}
}
- 查詢異步視頻生成任務的執行狀態和結果
- 實時狀態更新和進度跟蹤
- 任務完成時獲取生成的視頻
- 支持多語言返回(zh/en/ko/ja)
創建任務時傳入業務 ID
創建視頻任務時,可以在請求體頂層傳入client_business_id。該字段用於保存您系統內的訂單號、流水號或業務任務 ID,方便後續按業務 ID 查詢生成結果。
{
"model": "sora-2",
"client_business_id": "order_20260428_002",
"prompt": "海浪拍打着海岸",
"duration": 15,
"aspect_ratio": "16:9"
}
metadata.client_business_id 中,但推薦使用頂層字段。
Authorizations
string
必填
所有接口均需要使用 Bearer Token 進行認證獲取 API Key:訪問 API Key 管理頁面 獲取您的 API Key使用時在請求頭中添加:
Authorization: Bearer YOUR_API_KEY
Path Parameters
string
必填
視頻生成 API 返回的任務 ID。也可以傳創建任務時提交的
client_business_id,用於按客戶側業務 ID 查詢任務狀態和結果。如果創建視頻任務時傳入
client_business_id,可直接使用同一個狀態查詢接口:
GET /v1/videos/generations/{client_business_id}。業務 ID 會限定在當前 API Key 所屬用戶下查詢。curl --request GET \
--url 'https://toapis.com/v1/videos/generations/task_01K9S419324DREZFBWNSVXYR6H' \
--header 'Authorization: Bearer <token>'
import requests
import time
API_BASE = 'https://toapis.com'
API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx'
headers = {
'Authorization': f'Bearer {API_KEY}'
}
def get_video_status(task_id):
response = requests.get(f'{API_BASE}/v1/videos/generations/{task_id}', headers=headers)
return response.json()
def wait_for_video(task_id, max_attempts=60, interval=10):
for _ in range(max_attempts):
result = get_video_status(task_id)
status = result.get('status')
progress = result.get('progress', 0)
print(f"狀態: {status}, 進度: {progress}%")
if status == 'completed':
return result
elif status == 'failed':
raise Exception(f"任務失敗: {result}")
time.sleep(interval)
raise Exception("任務超時")
# 使用示例
task_id = "video_7497f4d5-3a88-44c7-923a-967fa7d941a0"
result = wait_for_video(task_id)
print(f"視頻URL: {result['result']['data'][0]['url']}")
const API_BASE = 'https://toapis.com';
const API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx';
async function getVideoStatus(taskId) {
const response = await fetch(`${API_BASE}/v1/videos/generations/${taskId}`, {
headers: {
'Authorization': `Bearer ${API_KEY}`
}
});
return response.json();
}
async function waitForVideo(taskId, maxAttempts = 60, interval = 10000) {
for (let i = 0; i < maxAttempts; i++) {
const result = await getVideoStatus(taskId);
const status = result.status;
const progress = result.progress || 0;
console.log(`狀態: ${status}, 進度: ${progress}%`);
if (status === 'completed') {
return result;
} else if (status === 'failed') {
throw new Error(`任務失敗: ${JSON.stringify(result)}`);
}
await new Promise(r => setTimeout(r, interval));
}
throw new Error('任務超時');
}
// 使用示例
const taskId = 'video_7497f4d5-3a88-44c7-923a-967fa7d941a0';
waitForVideo(taskId).then(result => {
console.log('視頻URL:', result.result.data[0].url);
console.log('格式:', result.result.data[0].format);
});
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
func getVideoStatus(taskId string) (map[string]interface{}, error) {
url := fmt.Sprintf("https://toapis.com/v1/videos/generations/%s", taskId)
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("Authorization", "Bearer <token>")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
return result, nil
}
func main() {
taskId := "video_7497f4d5-3a88-44c7-923a-967fa7d941a0"
for i := 0; i < 60; i++ {
result, _ := getVideoStatus(taskId)
status := result["status"].(string)
progress := int(result["progress"].(float64))
fmt.Printf("狀態: %s, 進度: %d%%\n", status, progress)
if status == "completed" {
fmt.Println("視頻生成完成!")
resultData := result["result"].(map[string]interface{})
dataArray := resultData["data"].([]interface{})
videoData := dataArray[0].(map[string]interface{})
fmt.Println("視頻URL:", videoData["url"])
break
}
time.Sleep(10 * time.Second)
}
}
{
"id": "video_7497f4d5-3a88-44c7-923a-967fa7d941a0",
"object": "generation.task",
"model": "sora-2",
"status": "queued",
"progress": 0,
"created_at": 1768380222
}
{
"id": "video_7497f4d5-3a88-44c7-923a-967fa7d941a0",
"object": "generation.task",
"model": "sora-2",
"status": "in_progress",
"progress": 65,
"created_at": 1768380222
}
{
"id": "video_7497f4d5-3a88-44c7-923a-967fa7d941a0",
"client_business_id": "order_20260428_001",
"object": "generation.task",
"model": "sora-2",
"status": "completed",
"progress": 100,
"created_at": 1768380222,
"completed_at": 1768380514,
"expires_at": 1768466914,
"result": {
"type": "video",
"data": [
{
"url": "https://files.toapis.com/sora/7712af45-ca35-4a15-b800-f20ea623665b.mp4",
"format": "mp4"
}
]
}
}
{
"id": "video_7497f4d5-3a88-44c7-923a-967fa7d941a0",
"object": "generation.task",
"model": "sora-2",
"status": "failed",
"progress": 0,
"created_at": 1768380222,
"error": {
"code": "generation_failed",
"message": "生成失敗: 內容違反了內容政策"
}
}
{
"error": {
"code": 404,
"message": "任務不存在",
"type": "not_found_error"
}
}
{
"error": {
"code": 401,
"message": "身份驗證失敗,請檢查您的API密鑰",
"type": "authentication_error"
}
}
Response
string
任務唯一標識符
string
客戶側業務 ID。僅當創建任務時傳入
client_business_id 時返回。string
對象類型,固定爲
generation.taskstring
使用的視頻生成模型
string
任務狀態
queued- 排隊等待處理in_progress- 處理中completed- 成功完成failed- 失敗
integer
任務進度百分比(0-100)
integer
任務創建時間(Unix 時間戳)
integer
任務完成時間(Unix 時間戳,僅完成時返回)
integer
視頻 URL 過期時間(Unix 時間戳,僅完成時返回)
object
object
模型工具用量。Seedance 2 啓用
tools: [{ "type": "web_search" }] 時,usage.tool_usage.web_search 表示實際聯網搜索次數;0 表示未搜索。任務狀態說明
| 狀態 | 說明 | 是否終態 | 建議操作 |
|---|---|---|---|
queued | 任務排隊等待處理 | ❌ | 等待 5-10 秒後重試查詢 |
in_progress | 任務正在處理中 | ❌ | 等待 10-15 秒後重試查詢 |
completed | 任務成功完成 | ✅ | 從 result.data[0].url 獲取視頻 |
failed | 任務處理失敗 | ✅ | 檢查 error 信息 |
輪詢策略建議
初始等待: 5 秒
輪詢間隔: 10 秒
最大等待: 600 秒(10分鐘)
典型耗時: 1-5 分鐘
Python 輪詢示例
import time
import random
import requests
def poll_video_task(task_id, api_key, max_wait=600):
"""輪詢視頻生成任務直到完成或超時"""
start_time = time.time()
interval = 10 # 10秒間隔
# 首次等待5秒
time.sleep(5)
while time.time() - start_time < max_wait:
response = requests.get(
f'https://toapis.com/v1/videos/generations/{task_id}',
headers={'Authorization': f'Bearer {api_key}'}
)
if response.status_code == 429:
retry_after = int(response.headers.get('Retry-After', interval))
time.sleep(retry_after + random.uniform(0, 1))
interval = min(interval * 2, 120)
continue
response.raise_for_status()
data = response.json()
print(f"狀態: {data['status']}, 進度: {data.get('progress', 0)}%")
if data['status'] == 'completed':
return {
'url': data['result']['data'][0]['url'],
'format': data['result']['data'][0].get('format'),
'expires_at': data.get('expires_at')
}
elif data['status'] == 'failed':
raise Exception(f"生成失敗: {data['error']['message']}")
time.sleep(interval + random.uniform(0, 1))
raise TimeoutError("任務超時")
視頻資源有效期
生成的視頻 URL 有效期爲 24 小時
- 請在有效期內下載保存視頻
expires_at字段標識視頻過期時間(Unix 時間戳)- 視頻過期後無法訪問,如需重新獲取,需要重新提交生成任務
- 縮略圖與視頻同步過期
常見錯誤
| 錯誤碼 | 錯誤類型 | 說明 |
|---|---|---|
| 400 | invalid_request | 請求參數無效 |
| 401 | unauthorized | 認證失敗,檢查 API Key |
| 402 | insufficient_quota | 餘額不足 |
| 404 | task_not_found | 任務不存在 |
| 422 | content_policy_violation | 內容違規 |
| 429 | rate_limit_exceeded | 請求頻率超限 |
| 500 | internal_error | 服務器內部錯誤 |
性能建議
視頻生成耗時較長,建議:
- 使用 ToAPIs 統一任務 Webhook:以 Webhook 為主,輪詢為後備
- 合理設置輪詢間隔:至少5~10秒並加入抖動;429 時讀取
Retry-After後指數退避 - 設置超時時間:長視頻生成可能需要5-10分鐘,請設置合理的超時
- 及時下載保存:視頻24小時後過期,請務必及時保存到自己的存儲
⌘I