本文へスキップ

メニュー

  • メディア
  • 料金プラン
  • ドキュメント
  • 言語:日本語

    グレー表示の言語では、このページはご覧いただけません。

    • English
    • Español
    • Português
    • Français
    • Deutsch
    • Italiano
    • Nederlands
    • Polski
    • 日本語
    • 한국어
    • Bahasa Indonesia
    • Tiếng Việt
    • Türkçe
    • العربية
    • ไทย
    • Български
    • Català
    • Hrvatski
    • Eesti
    • Magyar
    • Latviešu
    • Lietuvių
    • Srpski
    • Slovenčina
    • Slovenščina
    • Українська
    • Čeština
    • Română
    • Svenska
    • Dansk
    • Norsk bokmål
    • Suomi
    • עברית
    • हिन्दी
    • Tagalog
    • Bahasa Melayu
    • Ελληνικά
    • 简体中文
    • 繁體中文

人気のツール

クイックスタート

FilesOkay APIで動画を圧縮する手順を、5つのステップで説明します。各ステップでは、curl、Node.js、Pythonでのリクエストと、返ってくるレスポンスを紹介します。

このページの内容

始める前に

  • 有効なサブスクリプションのあるFilesOkayワークスペース。理由は制限とクレジットで説明しています。
  • Node.jsの手順にはNode.js 20以降、Pythonの手順にはPython 3.9以降とrequestsパッケージ。
  • 圧縮する動画。例ではlecture.mp4という名前にしています。

各ステップのコードをつなげて、1つのスクリプトを作ります。まずは次のコードから始めます。APIキーは環境変数FILESOKAY_KEYから読み込みます:

export FILESOKAY_KEY="filesokay_…"
// quickstart.mjs:`node quickstart.mjs`で実行します(Node.js 20以降)。
import fs from "node:fs";
import https from "node:https";
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";

const API = "https://api.filesokay.com/v1";

// APIを呼び出し、拒否された場合はそのエラーコードをthrowします。
async function api(method, path, body, headers = {}) {
  const res = await fetch(API + path, {
    method,
    headers: {
      Authorization: `Bearer ${process.env.FILESOKAY_KEY}`,
      "Content-Type": "application/json",
      ...headers,
    },
    body: body && JSON.stringify(body),
  });
  const data = res.status === 204 ? null : await res.json();
  if (!res.ok) throw new Error(`${data.code}: ${data.detail}`);
  return data;
}
# quickstart.py:`python quickstart.py`で実行します(Python 3.9以降、`pip install requests`が必要)。
import os
import time
import uuid

import requests

API = "https://api.filesokay.com/v1"


def api(method, path, body=None, headers=None):
    """APIを呼び出し、拒否された場合はそのエラーコードで例外を送出します。"""
    res = requests.request(
        method,
        API + path,
        json=body,
        headers={"Authorization": f"Bearer {os.environ['FILESOKAY_KEY']}", **(headers or {})},
    )
    data = res.json() if res.content else None
    if not res.ok:
        raise RuntimeError(f"{data['code']}: {data['detail']}")
    return data

1. APIキーを作成する

ワークスペースで設定を開き、APIキーでAPIキーを作成を選択します。キーに名前を付けて、本人確認を行います。キーは一度しか表示されないため、コピーしてFILESOKAY_KEYに設定してください。

2. ファイルをアップロードする

ファイル名とサイズを指定してアップロードを開始します。返ってきたURLにファイルを送信したら、アップロードを完了します。完了時にファイルが検査されます。

# ファイル名とサイズ(バイト)を指定して、アップロードを開始します。
curl https://api.filesokay.com/v1/uploads \
  -H "Authorization: Bearer $FILESOKAY_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "operation": "video.compress",
    "files": [{ "name": "lecture.mp4", "size": 12417467 }]
  }'

# ファイルをパート用URL(レスポンスのfiles[0].parts[0].url)に送信します。
curl -X PUT --upload-file lecture.mp4 "$PART_URL"

# アップロードを完了します。このときファイルが検査されます。
curl -X POST https://api.filesokay.com/v1/uploads/file_3cf0737aefa34b89b7b4443c9467d60c/complete \
  -H "Authorization: Bearer $FILESOKAY_KEY"
const name = "lecture.mp4";
const { size } = fs.statSync(name);

// ファイル名とサイズ(バイト)を指定して、アップロードを開始します。
const { files: [upload] } = await api("POST", "/uploads", {
  operation: "video.compress",
  files: [{ name, size }],
});

// ディスクから直接、ファイルをそのURLに送信します。URL自体に権限が含まれるため、APIキーは不要です。
await new Promise((resolve, reject) => {
  const req = https.request(upload.parts[0].url, {
    method: "PUT",
    headers: { "Content-Length": size },
  });
  req.on("response", (res) => {
    res.resume();
    if (res.statusCode === 200) resolve();
    else reject(new Error(`Upload failed: ${res.statusCode}`));
  });
  req.on("error", reject);
  fs.createReadStream(name).on("error", reject).pipe(req);
});

// アップロードを完了します。このときファイルが検査されます。
const uploaded = await api("POST", `/uploads/${upload.id}/complete`);
console.log(uploaded.check.state);
name = "lecture.mp4"

# ファイル名とサイズ(バイト)を指定して、アップロードを開始します。
upload = api("POST", "/uploads", {
    "operation": "video.compress",
    "files": [{"name": name, "size": os.path.getsize(name)}],
})["files"][0]

# ディスクから直接、ファイルをそのURLに送信します。URL自体に権限が含まれるため、APIキーは不要です。
with open(name, "rb") as f:
    requests.put(upload["parts"][0]["url"], data=f).raise_for_status()

# アップロードを完了します。このときファイルが検査されます。
uploaded = api("POST", f"/uploads/{upload['id']}/complete")
print(uploaded["check"]["state"])
レスポンス
{
  "id": "file_3cf0737aefa34b89b7b4443c9467d60c",
  "name": "lecture.mp4",
  "operation": "video.compress",
  "state": "uploaded",
  "size": 12417467,
  "created_at": "2026-12-03T08:59:54Z",
  "uploaded_at": "2026-12-03T09:00:00Z",
  "delete_at": "2026-12-04T09:00:00Z",
  "check": {
    "state": "proceed",
    "kind": "video",
    "type": "mp4",
    "facts": {
      "container": "mp4",
      "protection": "none",
      "attachments": [],
      "duration_ms": 20023,
      "frame_count": 600,
      "audio_tracks": [
        {
          "codec": "aac",
          "channels": 1,
          "sample_rate": 44100
        }
      ],
      "video_tracks": [
        {
          "hdr": "none",
          "codec": "h264",
          "width": 1280,
          "chroma": "420",
          "height": 720,
          "profile": "High",
          "rotation": 0,
          "bit_depth": 8,
          "frame_rate": 30,
          "interlaced": false,
          "variable_frame_rate": false
        }
      ],
      "data_end_bytes": 12417467,
      "subtitle_tracks": []
    },
    "facts_complete": true
  }
}

proceedは、そのファイルをジョブで使えることを示します。5 GBまでのファイルは1回のリクエストで送信できます。それより大きいファイルの送り方はファイルのアップロードをご覧ください。

3. ジョブを開始する

オペレーションとファイルを指定します。省略した設定にはデフォルト値が使われます。video.compressの場合は、バランスの取れた画質です。Idempotency-Keyヘッダーを付けると、安全に再試行できます。詳しくは安全な再試行をご覧ください。

curl https://api.filesokay.com/v1/jobs \
  -H "Authorization: Bearer $FILESOKAY_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{
    "operation": "video.compress",
    "inputs": [{ "file_id": "file_3cf0737aefa34b89b7b4443c9467d60c" }]
  }'
const job = await api(
  "POST",
  "/jobs",
  { operation: "video.compress", inputs: [{ file_id: upload.id }] },
  { "Idempotency-Key": crypto.randomUUID() },
);
console.log(job.id, job.status);
job = api(
    "POST",
    "/jobs",
    {"operation": "video.compress", "inputs": [{"file_id": upload["id"]}]},
    {"Idempotency-Key": str(uuid.uuid4())},
)
print(job["id"], job["status"])
レスポンス
{
  "id": "job_a1c9531eeb00434aba0058796f1ca517",
  "operation": "video.compress",
  "status": "waiting",
  "client_reference": null,
  "settings": {
    "audio": "keep",
    "codec": "same",
    "level": "balanced",
    "method": "quality",
    "frame_rate": "original",
    "resolution": "original",
    "output_format": "same"
  },
  "created_at": "2026-12-03T09:00:12Z",
  "reserved_credits": 2,
  "charged_credits": 0,
  "tasks": [
    {
      "id": "task_4256d03a73a741afa1821546a2bcba98",
      "status": "waiting",
      "progress": 0,
      "reserved_credits": 2,
      "inputs": [
        {
          "file_id": "file_3cf0737aefa34b89b7b4443c9467d60c",
          "name": "lecture.mp4"
        }
      ],
      "outputs": []
    }
  ]
}

ジョブはすぐに開始され、バックグラウンドで実行されます。この時点でクレジットが予約され、実際に使った分だけが差し引かれます。

4. ジョブの終了を待つ

ステータスがwaitingまたはprocessingでなくなるまで、5秒ごとにジョブを取得します。実際のアプリでは、Webhookでジョブの終了を受け取れるため、繰り返し問い合わせる必要はありません。

# ステータスがwaitingまたはprocessingでなくなるまで、数秒ごとに問い合わせます。
curl https://api.filesokay.com/v1/jobs/job_a1c9531eeb00434aba0058796f1ca517 \
  -H "Authorization: Bearer $FILESOKAY_KEY"
let current = job;
while (current.status === "waiting" || current.status === "processing") {
  await new Promise((resolve) => setTimeout(resolve, 5000));
  current = await api("GET", `/jobs/${job.id}`);
}
console.log(current.status);
current = job
while current["status"] in ("waiting", "processing"):
    time.sleep(5)
    current = api("GET", f"/jobs/{job['id']}")
print(current["status"])
レスポンス
{
  "id": "job_a1c9531eeb00434aba0058796f1ca517",
  "operation": "video.compress",
  "status": "completed",
  "client_reference": null,
  "settings": {
    "audio": "keep",
    "codec": "same",
    "level": "balanced",
    "method": "quality",
    "frame_rate": "original",
    "resolution": "original",
    "output_format": "same"
  },
  "created_at": "2026-12-03T09:00:12Z",
  "started_at": "2026-12-03T09:00:30Z",
  "finished_at": "2026-12-03T09:00:51Z",
  "reserved_credits": 2,
  "charged_credits": 1,
  "tasks": [
    {
      "id": "task_4256d03a73a741afa1821546a2bcba98",
      "status": "completed",
      "progress": 100,
      "reserved_credits": 2,
      "charged_credits": 1,
      "inputs": [
        {
          "file_id": "file_3cf0737aefa34b89b7b4443c9467d60c",
          "name": "lecture.mp4"
        }
      ],
      "outputs": [
        {
          "file_id": "file_8dd09e1ec2fb42c1940e4ef92a153a4e",
          "name": "lecture-compressed.mp4",
          "size": 7268734,
          "download_url": "https://…",
          "download_expires_at": "2026-12-06T09:00:51Z"
        }
      ]
    }
  ]
}

5. 結果をダウンロードする

完了した各タスクには結果が一覧で含まれ、それぞれに結果ファイルをその名前でダウンロードできるリンクが付いています。リンクの有効期間は最長7日間で、APIキーは不要です。

# リンクはジョブのtasks[0].outputs[0].download_urlにあります。APIキーは不要です。
curl -o lecture-compressed.mp4 "$DOWNLOAD_URL"
for (const task of current.tasks) {
  for (const output of task.outputs) {
    const res = await fetch(output.download_url);
    if (!res.ok) throw new Error(`${output.name}: ${res.status}`);
    await pipeline(Readable.fromWeb(res.body), fs.createWriteStream(output.name));
    console.log(`Saved ${output.name}: ${output.size} bytes`);
  }
}
for task in current["tasks"]:
    for output in task["outputs"]:
        with requests.get(output["download_url"], stream=True) as res:
            res.raise_for_status()
            with open(output["name"], "wb") as f:
                for chunk in res.iter_content(chunk_size=1 << 20):
                    f.write(chunk)
        print(f"Saved {output['name']}: {output['size']} bytes")

この例では、lecture.mp4が12.4 MBから7.3 MBになり、消費したのは1クレジットでした。

次のステップ

  • ジョブの実行

    設定、見積もり、バッチ処理、ステータス。

  • Webhook

    ポーリングは不要です。ジョブが終了したら署名付きメッセージが届きます。

  • エラーコード

    すべてのエラーをエラーコードで処理する方法です。