> ## Documentation Index
> Fetch the complete documentation index at: https://docs.toapis.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Get Video Task ステータス

> Query video generation task status and results

> [!NOTE]
>
> **中国本土のユーザー向け：** 中国本土のユーザーは `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.

> [!NOTE]
>
> [素材審査](https://docs.toapis.com/docs/ja/api-reference/videos/seedance-2/generation.md)が必要な 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

**Authorization** `string` *required*

All endpoints require Bearer Token authentication

Get your API Key:

Visit the [API Key Management Page](https://toapis.com/console/token) to get your API Key

Add it to the request header:

```
Authorization: Bearer YOUR_API_KEY
```

## Path パラメータ

**task\_id** `string` *required*

Task ID returned by the video generation API

```bash cURL theme={null}
curl --request GET \
  --url 'https://toapis.com/v1/videos/generations/task_01K9S419324DREZFBWNSVXYR6H' \
  --header 'Authorization: Bearer <token>'
```

```python Python theme={null}
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']}")
```

```javascript JavaScript theme={null}
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);
});
```

```go Go theme={null}
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)
    }
}
```

```json 200 - Queued theme={null}
{
  "id": "video_7497f4d5-3a88-44c7-923a-967fa7d941a0",
  "object": "generation.task",
  "model": "sora-2",
  "status": "queued",
  "progress": 0,
  "created_at": 1768380222
}
```

```json 200 - In Progress theme={null}
{
  "id": "video_7497f4d5-3a88-44c7-923a-967fa7d941a0",
  "object": "generation.task",
  "model": "sora-2",
  "status": "in_progress",
  "progress": 65,
  "created_at": 1768380222
}
```

```json 200 - Completed theme={null}
{
  "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": 1778656300,
  "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"
  }
}
```

```json 200 - Failed theme={null}
{
  "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"
  }
}
```

```json 404 theme={null}
{
  "error": {
    "code": 404,
    "message": "Task not found",
    "type": "not_found_error"
  }
}
```

```json 401 theme={null}
{
  "error": {
    "code": 401,
    "message": "Authentication failed, please check your API key",
    "type": "authentication_error"
  }
}
```

```json 200 - Seedance theme={null}
{
  "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": 1792486460,
  "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
    }
  }
}
```

## レスポンス

**id** `string`

Unique task identifier

**client\_business\_id** `string`

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

**object** `string`

Object type, always `generation.task`

**status** `string`

Task status

* `queued` - Queued for processing
* `in_progress` - Processing
* `completed` - Successfully completed
* `failed` - Failed

**progress** `integer`

Task progress percentage (0-100)

**model** `string`

Video generation model used

**updated\_at** `integer`

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

**created\_at** `integer`

Task creation time (Unix timestamp)

**finished\_at** `integer`

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

**completed\_at** `integer`

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

**expires\_at** `integer`

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

**result** `object`

Task result (only returned on success)

**Properties**

**type** `string`

Result type, always `video`

**data** `array`

Video data array

**Array item**

**url** `string`

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

**fallback\_url** `string`

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

**format** `string`

Video format (for example `mp4`)

**last\_frame\_url** `string`

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

**fallback\_last\_frame\_url** `string`

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

**generation** `object`

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

| フィールド | 型 | 説明 |
| - | - | - |
| `created_at`, `updated_at` | number | 上流タスクの作成と更新時刻, Unix タイムスタンプ. トップレベルのプラットフォーム時刻とは別です |
| `seed` | number | 乱数シード |
| `resolution` | string | 解像度 |
| `ratio` | string | アスペクト比 |
| `duration` | number | 生成時間, 秒 |
| `framespersecond` | number | フレームレート, フレーム/秒 |
| `service_tier` | string | サービスティア |
| `execution_expires_after` | number | 実行の有効期間, 秒 |
| `generate_audio` | boolean | 音声を生成するか |
| `draft` | boolean | ドラフトかどうか |
| `priority` | number | スケジュール優先度 |
| `output_format` | string | 出力形式 |

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

**usage** `object`

省略可能な課金数量, 動画トークン内訳, ツール使用回数です. 単位と省略条件は[タスクの使用量フィールド](https://docs.toapis.com/docs/ja/api-reference/account/pricing.md)を参照してください.

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

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

**billing** `object`

任意のプラットフォーム課金状態と確定済み請求額です. 課金状態は生成状態とは独立しており, `completed` でも確定済みとは限りません. オブジェクトがない場合も無料とは限りません. [料金と実際の請求額](https://docs.toapis.com/docs/ja/api-reference/account/pricing.md)を参照してください.

**Properties**

**status** `string`

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

**credits** `string`

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

**cost\_usd** `string`

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

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

**error** `object`

エラー information (only returned on failure)

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

**Properties**

**code** `any`

エラー code

**message** `any`

エラー description

## Task ステータス Reference

| ステータス | 説明 | Is Final | Recommended Action |
| - | - | - | - |
| `queued` | Task submitted, waiting in queue | ❌ | Wait 5-10 seconds, then query again |
| `in_progress` | Task is processing | ❌ | Wait 10-15 seconds, then query again |
| `completed` | Task completed successfully | ✅ | Get video from `result.data[0].url` |
| `failed` | Task 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

```python theme={null}
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

> [!WARNING]
>
> Generated video URLs are valid for **24 hours**
>
> * 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

## エラーと失敗理由

リクエストエラー, タスク失敗の具体的な原因, 復旧方法は[エラー早見表](https://docs.toapis.com/docs/ja/api-reference/errors.md)を参照してください. 照会成功後もタスク状態を確認し, HTTP ステータスと業務コードを区別してください.

## Performance Tips

> [!NOTE]
>
> Video generation takes longer, recommendations:
>
> 1. **ToAPIs Task Webhook**: [Webhook](https://docs.toapis.com/docs/ja/api-reference/webhooks/task-webhooks.md) を主経路、照会をフォールバックにします
> 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 expire after 24 hours, save to your storage immediately

[非同期タスクのレート制限](https://docs.toapis.com/docs/ja/api-reference/rate-limits/async-tasks.md)を参照してください。バッチ照会は最大100件です。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.