ToAPIsToAPIs

Get Video Task ステータス

Query video generation task status and results

GET
/v1/videos/generations/{task_id}

中国本土のユーザー向け: 中国本土のユーザーは https://toapis.cn を API エンドポイント(Base URL)としてご利用ください。本ドキュメント内の例では https://toapis.com を https://toapis.cn に置き換えてください。

  • Query async video generation task execution status and results
  • Real-time status updates and progress tracking
  • Get generated videos when task completes
  • Multi-language support (zh/en/ko/ja)

All video generation tasks are executed asynchronously. After submitting a task, you need to query the status and results via the query endpoint.

素材審査が必要な Seedance の動画タスクもこの API で照会します. queued には素材の準備や審査待ちも含まれ, タスクの受理は動画生成開始を意味しません. 準備期限は既定で 1 ラウンド 20 分で, その後の動画生成時間は含みません. 失敗時は error.message を確認します.

通常の画像と動画のタスクは GET /v1/tasks/{task_id} でも照会でき, usage と billing の定義は共通です. このページは冒頭に記載した生成タスク照会パスのレスポンスを説明します.

サンプルはフィールドを示すもので, モデルの現在の価格や固定の課金方式を示すものではありません. 実際のタスクで返されたフィールドと金額を確認してください.

Seedance の元の URL と代替 URL

元の URL の配信が有効な Seedance タスクでは, result.data[].url は上流の元の動画 URL を保持します. url を優先し, アクセスできない場合にのみ同じ結果項目の fallback_url に切り替えてください. プラットフォームはクライアントの地域に応じて URL を自動で切り替えません.

代替フィールドは任意で, コピーが利用可能な場合のみ返されます. 元の URL の配信が無効, コピーが利用できない, または過去のタスクにコピーがない場合は省略されることがあります. 省略は生成失敗を意味しません. 最終フレームも last_frame_url を優先し, アクセスできない場合のみ fallback_last_frame_url を使用します. 代替 URL は元の URL の有効期限を延長しません. 長期保存が必要な場合は速やかにダウンロードしてください.

Authorizations

Authorizationstringヘッダー必須

All endpoints require Bearer Token authentication

Get your API Key:

Visit the API Key Management Page to get your API Key

Add it to the request header:

Authorization: Bearer YOUR_API_KEY

Path パラメータ

task_idstringパス必須

Task ID returned by the video generation API

リクエスト例

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: {status}, Progress: {progress}%")

        if status == 'completed':
            return result
        elif status == 'failed':
            raise Exception(f"Task failed: {result}")

        time.sleep(interval)

    raise Exception("Task timeout")

# Usage example
task_id = "task_01K9S419324DREZFBWNSVXYR6H"
result = wait_for_video(task_id)
print(f"Video 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: ${status}, Progress: ${progress}%`);

    if (status === 'completed') {
      return result;
    } else if (status === 'failed') {
      throw new Error(`Task failed: ${JSON.stringify(result)}`);
    }

    await new Promise(r => setTimeout(r, interval));
  }

  throw new Error('Task timeout');
}

// Usage example
const taskId = 'task_01K9S419324DREZFBWNSVXYR6H';
waitForVideo(taskId).then(result => {
  console.log('Video URL:', result.result.data[0].url);
  console.log('Format:', 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 := "task_01K9S419324DREZFBWNSVXYR6H"

    for i := 0; i < 60; i++ {
        result, _ := getVideoStatus(taskId)
        status := result["status"].(string)
        progress := int(result["progress"].(float64))

        fmt.Printf("Status: %s, Progress: %d%%\n", status, progress)

        if status == "completed" {
            fmt.Println("Video generation completed!")
            resultData := result["result"].(map[string]interface{})
            dataArray := resultData["data"].([]interface{})
            videoData := dataArray[0].(map[string]interface{})
            fmt.Println("Video 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": "tsk_vid_01KRDG4S50XXXXXXXXXXXXXXX",
  "object": "generation.task",
  "model": "seedance-2",
  "status": "completed",
  "progress": 100,
  "created_at": 1778569600,
  "finished_at": 1778569900,
  "completed_at": 1778569900,
  "expires_at": 1781161900,
  "result": {
    "type": "video",
    "data": [
      {
        "url": "https://files.toapis.com/videos/tsk_vid_01KRDG4S50XXXXXXXXXXXXXXX/********_********.mp4",
        "format": "mp4"
      }
    ]
  },
  "billing": {
    "status": "settled",
    "credits": "100",
    "cost_usd": "0.5"
  }
}
{
  "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": "Generation failed: Content violates the content policy"
  }
}
{
  "error": {
    "code": 404,
    "message": "Task not found",
    "type": "not_found_error"
  }
}
{
  "error": {
    "code": 401,
    "message": "Authentication failed, please check your API key",
    "type": "authentication_error"
  }
}
{
  "id": "task_seedance_example",
  "object": "generation.task",
  "model": "seedance-2-global",
  "client_business_id": "order_123",
  "status": "completed",
  "progress": 100,
  "created_at": 1792400000,
  "updated_at": 1792400061,
  "finished_at": 1792400060,
  "completed_at": 1792400060,
  "expires_at": 1794992060,
  "result": {
    "type": "video",
    "data": [
      {
        "url": "https://cdn.example/result.mp4",
        "fallback_url": "https://files.toapis.com/videos/task_seedance_example/result.mp4",
        "format": "mp4",
        "last_frame_url": "https://cdn.example/last-frame.jpg",
        "fallback_last_frame_url": "https://files.toapis.com/videos/task_seedance_example/last-frame.jpg"
      }
    ]
  },
  "usage": {
    "charge_type": "per_token",
    "billed_tokens": 87300,
    "completion_tokens": 87300,
    "total_tokens": 87300
  },
  "billing": {
    "status": "settled",
    "credits": "87.3",
    "cost_usd": "0.4365"
  },
  "generation": {
    "duration": 5,
    "resolution": "720p",
    "ratio": "16:9",
    "generate_audio": true,
    "usage": {
      "completion_tokens": 87300,
      "total_tokens": 87300
    }
  }
}

レスポンス

idstring

Unique task identifier

client_business_idstring

省略可能な顧客側の業務 ID. タスク作成時に client_business_id を指定した場合のみ返します.

objectstring

Object type, always generation.task

statusstring

Task status

  • queued - Queued for processing
  • in_progress - Processing
  • completed - Successfully completed
  • failed - Failed
progressinteger

Task progress percentage (0-100)

modelstring

Video generation model used

updated_atinteger

省略可能なプラットフォームのタスク更新時刻, Unix タイムスタンプ. 現在は Seedance Global で返します. generation.updated_at は上流の更新時刻です.

created_atinteger

Task creation time (Unix timestamp)

finished_atinteger

タスク終了時刻, Unix タイムスタンプ. この照会パスでは, 成功または失敗したタスクに保存済みの終了時刻がある場合に返します.

completed_atinteger

Task completion time (Unix timestamp, only returned when completed)

expires_atinteger

Video URL expiration time (Unix timestamp, only returned on completion)

resultobject

Task result (only returned on success)

Properties
typestring

Result type, always video

dataarray

Video data array

Array item
urlstring

動画のメイン URL. 元の URL の配信が有効な Seedance タスクでは上流の元の URL を保持します. この URL を優先してください.

fallback_urlstring

コピーが利用可能な場合のみ返される任意の代替動画 URL. メイン URL にアクセスできない場合のみ使用し, url を置き換えません.

formatstring

Video format (for example mp4)

last_frame_urlstring

生成動画の最終フレーム画像 URL。return_last_frame: true で作成し、モデルがフレームを返した場合のみ含まれます。

fallback_last_frame_urlstring

フレームのコピーが利用可能な場合に返される任意の代替 URL. last_frame_url にアクセスできない場合のみ使用します.

generationobject

省略可能な Seedance の生成メタデータです. 保存済みで公開可能なフィールドのみ返し, デフォルト値は補完しません. 生成パラメータであり, トップレベルの usage にある課金数量の代わりにはなりません.

フィールド型説明
created_at, updated_atnumber上流タスクの作成と更新時刻, Unix タイムスタンプ. トップレベルのプラットフォーム時刻とは別です
seednumber乱数シード
resolutionstring解像度
ratiostringアスペクト比
durationnumber生成時間, 秒
framespersecondnumberフレームレート, フレーム/秒
service_tierstringサービスティア
execution_expires_afternumber実行の有効期間, 秒
generate_audioboolean音声を生成するか
draftbooleanドラフトかどうか
prioritynumberスケジュール優先度
output_formatstring出力形式

generation.usage は既存の互換フィールドで, completion_tokens と total_tokens を含む場合があります. 欠落する場合や最終課金数量と異なる場合があります. トップレベルの usage に加算せず, 課金数量にはトップレベルの usage を使用してください.

usageobject

省略可能な課金数量, 動画トークン内訳, ツール使用回数です. 単位と省略条件はタスクの使用量フィールドを参照してください.

フィールド型説明
charge_typestring課金方式: per_request, per_second, per_token
requestsinteger課金対象のリクエスト数. per_request の場合に返されます. Midjourney 動画で有効な batch_size は課金回数に含まれます
billed_tokensinteger料金計算に使用したトークン数. per_token の場合に返されます
output_secondsinteger課金対象となる出力動画の長さ, 整数秒. per_second の場合に返されます
input_secondsinteger課金対象となる入力動画の長さ, 整数秒. ゼロの場合は省略します
input_imagesinteger無料枠を差し引いた課金対象の入力画像数. ゼロの場合は省略します
input_tokens, output_tokens, prompt_tokens, completion_tokens, total_tokensinteger動画モデルが報告したトークン数. 提供されたとおりに返され, トークン課金の確定処理で total_tokens が補完される場合があります
tool_usageobjectツール使用回数: web_search, image_search, grounding_queries. 使用した場合に返されます

charge_type から input_images までは課金数量であり, billing.status=settled と同時にのみ返されます. 固定料金の動画は提出時に確認された数量を, 実際の長さやトークンで確定する動画は最終確定数量を返します. 返されないフィールドは省略され, ゼロで補完されません.

billingobject

任意のプラットフォーム課金状態と確定済み請求額です. 課金状態は生成状態とは独立しており, completed でも確定済みとは限りません. オブジェクトがない場合も無料とは限りません. 料金と実際の請求額を参照してください.

Properties
statusstring

pending: 生成中, 確定待ち, または返金が未確認の状態. 金額は省略されます. settled: 最終請求額が確定済み. 提出時に一括課金される固定料金の動画を含み, 実際の金額を返します. refunded: 返金済み, または失敗後に正味請求額なしと確認済み. 両方の金額は "0" です.

creditsstring

実際に請求された ToAPIs Credits. 10 進文字列です. settled または refunded の場合のみ返されます.

cost_usdstring

同じ請求額の USD 金額. 10 進文字列です. credits と同じ条件で返され, 割引と倍率を含み, プロバイダー原価ではありません.

タスク Webhook の data.billing も同じ確認条件と値を使います.

errorobject

エラー information (only returned on failure)

エラーコードとメッセージは通常文字列です. Seedance Global は error.code と error.message に上流の元の JSON 値を保持し, 数値や null もそのまま返します. 上流にないフィールドをプラットフォームのデフォルト値で補完しません.

Properties
codeany

エラー code

messageany

エラー description

Task ステータス Reference

ステータス説明Is FinalRecommended Action
queuedTask submitted, waiting in queue❌Wait 5-10 seconds, then query again
in_progressTask is processing❌Wait 10-15 seconds, then query again
completedTask completed successfully✅Get video from result.data[0].url
failedTask processing failed✅Check error info

Polling Strategy

Initial wait: 5 seconds
Polling interval: 10 seconds
Max wait: 600 seconds (10 minutes)
Typical time: 1-5 minutes

Python Polling Example

import time
import random
import requests

def poll_video_task(task_id, api_key, max_wait=600):
    """Poll video generation task until completion or timeout"""
    start_time = time.time()
    interval = 10  # 10 second interval

    # Initial 5 second wait
    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"Status: {data['status']}, Progress: {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"Generation failed: {data['error']['message']}")

        time.sleep(interval + random.uniform(0, 1))

    raise TimeoutError("Task timeout")

Resource Expiration

Generated videos are retained for 30 days

  • Please download and save videos within the validity period
  • expires_at field indicates video expiration time (Unix timestamp)
  • Expired videos cannot be accessed; to regenerate, submit a new task
  • Thumbnails expire simultaneously with videos

エラーと失敗理由

リクエストエラー, タスク失敗の具体的な原因, 復旧方法はエラー早見表を参照してください. 照会成功後もタスク状態を確認し, HTTP ステータスと業務コードを区別してください.

Performance Tips

Video generation takes longer, recommendations:

  1. ToAPIs Task Webhook: Webhook を主経路、照会をフォールバックにします
  2. 照会間隔: 5~10秒以上と jitter。429 は Retry-After を読み exponential backoff
  3. Set Timeout: Long videos may take 5-10 minutes, set reasonable timeout
  4. Download Promptly: Videos are retained for 30 days, save them to your storage before they expire

非同期タスクのレート制限を参照してください。バッチ照会は最大100件です。