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

# 動画のダウンロード

> 生成が完了した動画のファイルデータをダウンロード

## はじめに

動画ダウンロードエンドポイントは、生成が完了した動画のファイルデータを取得するために使用します。

<Warning>
  このエンドポイントに対応しているのはSora 2モデルのみです。ほかのモデル（Veo、Doubao Seedance）は、タスク照会のレスポンスで動画URLを直接返すため、追加のダウンロード手順は不要です。
</Warning>

## 認証

Bearerトークン。例: `Bearer sk-xxxxxxxxxx`

## クエリパラメータ

<ParamField query="id" type="string" required>
  動画ID。タスク照会エンドポイントが返す`task_id`です
</ParamField>

## cURLの例

```bash theme={null}
curl -X GET "https://api.mixroute.ai/v1/video/generations/download?id=video_69095b4ce0048190893a01510c0c98b0" \
  -H "Authorization: Bearer sk-xxxxxxxxxx"
```

## レスポンス例

```json theme={null}
{
  "success": true,
  "generation_id": "video_69095b4ce0048190893a01510c0c98b0",
  "task_id": "video_69095b4ce0048190893a01510c0c98b0",
  "format": "mp4",
  "size": 15728640,
  "base64": "AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAB...",
  "data_url": "data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAB..."
}
```

## レスポンスフィールド

| フィールド | 型 | 説明 |
| - | - | - |
| `success` | boolean | リクエストが成功したかどうか |
| `generation_id` | string | 生成ID（videoIdと同じ） |
| `task_id` | string | タスクID |
| `format` | string | 動画形式（`"mp4"`に固定） |
| `size` | number | 動画ファイルのサイズ（バイト） |
| `base64` | string | Base64エンコードされた動画データ |
| `data_url` | string | Data URL形式の動画データ。フロントエンドの`<video>`タグで直接使用できます |

## 利用ガイド

### フロントエンドでdata\_urlを使用する

`data_url`フィールドは、HTMLの`<video>`タグで直接使用できます。

```html theme={null}
<video src="data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAB..." controls></video>
```

### ファイルのダウンロードと保存

#### Node.js（サーバー側）

MixRouteキーはサーバー側に保持してください。ブラウザーのコードにはキーを埋め込まず、ご自身のバックエンドを呼び出してください。このエンドポイントは、生のMP4バイト列ではなく、Base64を含むJSONを返します。

```javascript theme={null}
import { writeFile } from "node:fs/promises";

const apiKey = process.env.MIXROUTE_API_KEY;
if (!apiKey) throw new Error("MIXROUTE_API_KEY is required");
const url = new URL("https://api.mixroute.ai/v1/video/generations/download");
url.searchParams.set("id", "TASK_ID");
const response = await fetch(url, {
  headers: { Authorization: "Bearer " + apiKey },
  signal: AbortSignal.timeout(120000),
});
if (!response.ok) throw new Error("Download HTTP error: " + response.status);
const data = await response.json();
if (data.success !== true || typeof data.base64 !== "string" || !data.base64) {
  throw new Error(data.message || "No downloadable video in response");
}
await writeFile("video.mp4", Buffer.from(data.base64, "base64"));
```

#### Pythonの例

```python theme={null}
import base64
import os
from pathlib import Path
import requests

def download_video(task_id, output_path="video.mp4"):
    response = requests.get(
        "https://api.mixroute.ai/v1/video/generations/download",
        params={"id": task_id},
        headers={"Authorization": "Bearer " + os.environ["MIXROUTE_API_KEY"]},
        timeout=120,
    )
    response.raise_for_status()
    result = response.json()
    if result.get("success") is not True or not result.get("base64"):
        raise RuntimeError(result.get("message") or "No downloadable video in response")
    video = base64.b64decode(result["base64"], validate=True)
    Path(output_path).write_bytes(video)
    return output_path

if __name__ == "__main__":
    print(download_video("TASK_ID"))
```

## ワークフロー全体の例（Sora 2）

### 1. 動画生成タスクを送信

```bash theme={null}
curl -X POST "https://api.mixroute.ai/v1/video/generations" \
  -H "Authorization: Bearer sk-xxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "sora-2",
    "prompt": "A cute kitten playing in the garden",
    "seconds": "4",
    "size": "720x1280"
  }'
```

レスポンス：

```json theme={null}
{
  "task_id": "video_69095b4ce0048190893a01510c0c98b0",
  "status": "submitted",
  "format": "mp4"
}
```

### 2. タスクの状態を照会（成功するまでポーリング）

```bash theme={null}
curl -X GET "https://api.mixroute.ai/v1/video/generations/video_69095b4ce0048190893a01510c0c98b0" \
  -H "Authorization: Bearer sk-xxxxxxxxxx"
```

照会で成功の終端ステータス（`succeeded`、`SUCCESS`、または`completed`）が報告されたら、次のステップに進みます。

### 3. 動画ファイルをダウンロード

```bash theme={null}
curl -X GET "https://api.mixroute.ai/v1/video/generations/download?id=video_69095b4ce0048190893a01510c0c98b0" \
  -H "Authorization: Bearer sk-xxxxxxxxxx"
```

## 注意事項

* ダウンロードエンドポイントはBase64でエンコードされた動画データを返します。フロントエンドでの直接表示や保存に適しています
* 大きなファイルには、ストリーミングダウンロードまたはURLからの直接ダウンロードを検討してください
* 動画形式はMP4に固定されています

<RequestExample>
  ```bash cURL theme={null}
  curl --request GET \
    --url 'https://api.mixroute.ai/v1/video/generations/download?id=video_xxx' \
    --header 'Authorization: Bearer sk-xxxxxxxxxx'
  ```

  ```python Python theme={null}
  import requests

  url = "https://api.mixroute.ai/v1/video/generations/download"
  params = {"id": "video_xxx"}
  headers = {"Authorization": "Bearer sk-xxxxxxxxxx"}

  response = requests.get(url, params=params, headers=headers)
  print(response.json())
  ```

  ```javascript Node.js theme={null}
  import { writeFile } from "node:fs/promises";

  const apiKey = process.env.MIXROUTE_API_KEY;
  if (!apiKey) throw new Error("MIXROUTE_API_KEY is required");
  const url = new URL("https://api.mixroute.ai/v1/video/generations/download");
  url.searchParams.set("id", "TASK_ID");
  const response = await fetch(url, {
    headers: { Authorization: "Bearer " + apiKey },
    signal: AbortSignal.timeout(120000),
  });
  if (!response.ok) throw new Error("Download HTTP error: " + response.status);
  const data = await response.json();
  if (data.success !== true || typeof data.base64 !== "string" || !data.base64) {
    throw new Error(data.message || "No downloadable video in response");
  }
  await writeFile("video.mp4", Buffer.from(data.base64, "base64"));
  ```

  ```php PHP theme={null}
  <?php
  $client = new GuzzleHttp\Client();
  $response = $client->get('https://api.mixroute.ai/v1/video/generations/download', [
      'headers' => [
          'Authorization' => 'Bearer sk-xxxxxxxxxx'
      ],
      'query' => ['id' => 'video_xxx']
  ]);
  echo $response->getBody();
  ```

  ```go Go theme={null}
  package main

  import (
      "net/http"
  )

  func main() {
      req, _ := http.NewRequest("GET", "https://api.mixroute.ai/v1/video/generations/download?id=video_xxx", nil)
      req.Header.Set("Authorization", "Bearer sk-xxxxxxxxxx")
      http.DefaultClient.Do(req)
  }
  ```

  ```java Java theme={null}
  import java.net.http.*;
  import java.net.URI;

  HttpClient client = HttpClient.newHttpClient();
  HttpRequest request = HttpRequest.newBuilder()
      .uri(URI.create("https://api.mixroute.ai/v1/video/generations/download?id=video_xxx"))
      .header("Authorization", "Bearer sk-xxxxxxxxxx")
      .GET()
      .build();
  HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
  System.out.println(response.body());
  ```

  ```ruby Ruby theme={null}
  require 'net/http'
  require 'json'

  uri = URI('https://api.mixroute.ai/v1/video/generations/download?id=video_xxx')
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  request = Net::HTTP::Get.new(uri)
  request['Authorization'] = 'Bearer sk-xxxxxxxxxx'

  response = http.request(request)
  puts response.body
  ```
</RequestExample>

<ResponseExample>
  ```json Response theme={null}
  {
    "success": true,
    "generation_id": "video_xxx",
    "task_id": "video_xxx",
    "format": "mp4",
    "size": 15728640,
    "base64": "AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDE...",
    "data_url": "data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDE..."
  }
  ```
</ResponseExample>


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