メインコンテンツへスキップ
実験的 API: この API は実験的であり、変更される可能性があります。エンドポイント、リクエスト/レスポンス形式、および動作は予告なく変更される場合があります。

Comfy Cloud API

Comfy Cloud API は、Comfy Cloud インフラストラクチャ上でワークフローを実行するためのプログラムによるアクセスを提供します。この API はローカルの ComfyUI の API と互換性があり、既存の統合を簡単に移行できます。
サブスクリプションが必要: API を介してワークフローを実行するには、有効な Comfy Cloud サブスクリプションが必要です。詳細は料金プランをご覧ください。

ベース URL

https://cloud.comfy.org

認証

すべての API リクエストには、X-API-Key ヘッダーを介して API キーを渡す必要があります。

API キーの取得

1

Visit https://platform.comfy.org/login and Log In

Please visit https://platform.comfy.org/login and log in with the corresponding accountVisit Platform Login Page
2

Click `+ New` in API Keys to Create an API Key

Click + New in API Keys to create an API KeyCreate API Key
3

Enter API Key Name

Enter API Key Name
  1. (Required) Enter the API Key name,
  2. Click Generate to create
4

Save the Obtained API Key

Obtain API Key
Since the API Key is only visible upon first creation, please save it immediately after creation. It cannot be viewed later, so please keep it safe. Please note that you should not share your API Key with others. Once it leaked, you can delete it and create a new one.
API キーは安全に保管してください。バージョン管理システムにコミットしたり、公開で共有したりしないでください。

API キーの使用

すべてのリクエストで X-API-Key ヘッダーに API キーを渡します:
curl -X GET "https://cloud.comfy.org/api/user" \
  -H "X-API-Key: $COMFY_CLOUD_API_KEY"

核心概念

ワークフロー

ComfyUI ワークフローは、ノードのグラフを記述する JSON オブジェクトです。API は「API 形式」のワークフローを受け付けます(ノード ID をキーとし、class_type、inputs などを含む)。この形式は、ComfyUI フロントエンドの「Save (API Format)」オプションによって生成されます。

ジョブ

ワークフローを送信すると、ジョブが作成されます。ジョブは非同期で実行されます:
  1. POST /api/prompt を介してワークフローを送信
  2. prompt_id(ジョブ ID)を受け取る
  3. WebSocket を介して進捗を監視するか、ステータスをポーリング
  4. 完了時に出力を取得

並列実行(同時ジョブ)

API ユーザーは、前のジョブの完了を待たずに、複数のワークフローを同時に送信できます。複数の POST /api/prompt リクエストを送信するだけです。特別なヘッダーやパラメーターは必要ありません。ディスパッチャーは、サブスクリプションティアの制限まで、それらを並列で実行します。
サブスクリプションティア同時ジョブ数
Free1
Standard1
Creator3
Pro5
同時実行制限を超えて送信されたジョブは、通常通りキューに入れられ、スロットが空くと自動的に実行されます。
並列実行は現在、API を介してのみ利用可能です。サブスクリプションの詳細は料金プランをご覧ください。

例:複数のジョブを並列で送信

import os
import json
import asyncio
import aiohttp

BASE_URL = "https://cloud.comfy.org"
API_KEY = os.environ["COMFY_CLOUD_API_KEY"]

async def submit_workflow(session, workflow):
    """単一のワークフローを送信し、prompt_id を返します。"""
    async with session.post(
        f"{BASE_URL}/api/prompt",
        headers={"X-API-Key": API_KEY, "Content-Type": "application/json"},
        json={"prompt": workflow},
    ) as response:
        result = await response.json()
        return result["prompt_id"]

async def main():
    with open("workflow_api.json") as f:
        base_workflow = json.load(f)

    # シードを変更してバリエーションを作成
    workflows = []
    for seed in [42, 123, 456]:
        workflow = json.loads(json.dumps(base_workflow))
        workflow["3"]["inputs"]["seed"] = seed
        workflows.append(workflow)

    # すべてのワークフローを同時に送信
    async with aiohttp.ClientSession() as session:
        prompt_ids = await asyncio.gather(
            *[submit_workflow(session, wf) for wf in workflows]
        )

    for pid in prompt_ids:
        print(f"Job submitted: {pid}")

    # 各ジョブをポーリングまたは WebSocket で監視...

asyncio.run(main())

出力

生成されたコンテンツ(画像、動画、音声)はクラウドストレージに保存されます。出力ファイルは /api/view エンドポイントを介してダウンロードできます。このエンドポイントは、一時署名付き URL への 302 リダイレクトを返します。

クイックスタート

ワークフローの送信、進捗の監視、出力の取得方法を示す完全な例を以下に示します:

ステップ 1:ワークフローの送信

curl -X POST "https://cloud.comfy.org/api/prompt" \
  -H "X-API-Key: $COMFY_CLOUD_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"prompt": '"$(cat workflow_api.json)"'}'

ステップ 2:ジョブの進捗を監視

ポーリングまたは WebSocket を使用して、ジョブの完了を監視できます。

オプション A:ポーリング(シンプル)

Job Status Values: The API returns one of the following status values:
StatusDescription
pendingJob is queued and waiting to start
in_progressJob is currently executing
completedJob finished successfully
failedJob encountered an error
cancelledJob was cancelled by user
# Poll for job completion
curl -X GET "$BASE_URL/api/job/{prompt_id}/status" \
  -H "X-API-Key: $COMFY_CLOUD_API_KEY"

# Response examples:
# {"status": "pending"}      - Job is queued
# {"status": "in_progress"}  - Job is currently running
# {"status": "completed"}    - Job finished successfully
# {"status": "failed"}       - Job encountered an error
# {"status": "cancelled"}    - Job was cancelled

オプション B:WebSocket(リアルタイム進捗)

リアルタイムの進捗更新と出力メタデータの収集には:
async function listenForCompletion(
  promptId: string,
  timeout: number = 300000
): Promise<Record<string, any>> {
  const wsUrl = `wss://cloud.comfy.org/ws?clientId=${crypto.randomUUID()}&token=${API_KEY}`;
  const outputs: Record<string, any> = {};

  return new Promise((resolve, reject) => {
    const ws = new WebSocket(wsUrl);
    const timer = setTimeout(() => {
      ws.close();
      reject(new Error(`Job did not complete within ${timeout / 1000}s`));
    }, timeout);

    ws.onmessage = (event) => {
      const data = JSON.parse(event.data);
      const msgType = data.type;
      const msgData = data.data ?? {};

      // Filter to our job
      if (msgData.prompt_id !== promptId) return;

      if (msgType === "executing") {
        const node = msgData.node;
        if (node) {
          console.log(`Executing node: ${node}`);
        } else {
          console.log("Execution complete");
        }
      } else if (msgType === "progress") {
        console.log(`Progress: ${msgData.value}/${msgData.max}`);
      } else if (msgType === "executed" && msgData.output) {
        outputs[msgData.node] = msgData.output;
      } else if (msgType === "execution_success") {
        console.log("Job completed successfully!");
        clearTimeout(timer);
        ws.close();
        resolve(outputs);
      } else if (msgType === "execution_error") {
        const errorMsg = msgData.exception_message ?? "Unknown error";
        clearTimeout(timer);
        ws.close();
        reject(new Error(`Execution error: ${errorMsg}`));
      }
    };

    ws.onerror = (err) => {
      clearTimeout(timer);
      reject(err);
    };
  });
}

// Wait for completion and collect outputs
const outputs = await listenForCompletion(promptId);
詳細なメッセージタイプとバイナリプレビュー画像の処理については、WebSocket リファレンスをご覧ください。

ステップ 3:出力のダウンロード

ジョブが完了したら、生成されたファイルをダウンロードします。WebSocket から返される outputs オブジェクト(または履歴エンドポイントを介して利用可能)には、ノード ID ごとに整理された出力データが含まれています。各ノードの出力には、ファイルメタデータを含む imagesvideo、または audio 配列が含まれる場合があります。 出力構造の例:
{
  "9": {
    "images": [
      {
        "filename": "ComfyUI_00001_.png",
        "subfolder": "",
        "type": "output"
      }
    ]
  }
}
ノード ID(この例では "9")は、ワークフロー内の SaveImage または他の出力ノードに対応します。これらの ID は、ワークフロー JSON ファイルを開き、class_typeSaveImageVHS_VideoCombine などのノードを探すことで見つけることができます。
# Download a single output file (follow 302 redirect with -L)
curl -L "$BASE_URL/api/view?filename=output.png&subfolder=&type=output" \
  -H "X-API-Key: $COMFY_CLOUD_API_KEY" \
  -o output.png
/api/view エンドポイントは、一時署名付き URL への 302 リダイレクトを返します。ファイルをダウンロードするには、HTTP クライアントがリダイレクトに従う必要があります。

完全な例

以下は、3 つのすべてのステップを組み合わせた完全なエンドツーエンドの例です:
import { readFile, writeFile } from "fs/promises";

const BASE_URL = "https://cloud.comfy.org";
const API_KEY = process.env.COMFY_CLOUD_API_KEY!;

async function main() {
  // 1. Load and modify workflow
  const workflow = JSON.parse(await readFile("workflow_api.json", "utf-8"));
  workflow["3"].inputs.seed = 42;
  workflow["6"].inputs.text = "a beautiful sunset";

  // 2. Submit workflow
  const response = await fetch(`${BASE_URL}/api/prompt`, {
    method: "POST",
    headers: { "X-API-Key": API_KEY, "Content-Type": "application/json" },
    body: JSON.stringify({ prompt: workflow }),
  });
  const { prompt_id } = await response.json();
  console.log(`Job submitted: ${prompt_id}`);

  // 3. Poll for completion
  while (true) {
    const statusRes = await fetch(`${BASE_URL}/api/job/${prompt_id}/status`, {
      headers: { "X-API-Key": API_KEY },
    });
    const { status } = await statusRes.json();

    if (status === "completed") break;
    if (["failed", "cancelled"].includes(status)) {
      throw new Error(`Job ${status}`);
    }
    await new Promise((resolve) => setTimeout(resolve, 2000));
  }

  // 4. Get outputs via history endpoint
  const historyRes = await fetch(`${BASE_URL}/api/history_v2/${prompt_id}`, {
    headers: { "X-API-Key": API_KEY },
  });
  const history = await historyRes.json();
  const outputs = history.outputs;

  // 5. Download output files
  for (const nodeOutputs of Object.values(outputs)) {
    for (const fileInfo of (nodeOutputs as any).images ?? []) {
      const params = new URLSearchParams({
        filename: fileInfo.filename,
        subfolder: fileInfo.subfolder ?? "",
        type: "output",
      });
      const viewRes = await fetch(`${BASE_URL}/api/view?${params}`, {
        headers: { "X-API-Key": API_KEY },
        redirect: "manual",
      });
      const signedUrl = viewRes.headers.get("location")!;
      const fileRes = await fetch(signedUrl);
      await writeFile(`./${fileInfo.filename}`, Buffer.from(await fileRes.arrayBuffer()));
      console.log(`Downloaded: ${fileInfo.filename}`);
    }
  }
}

main();

利用可能なエンドポイント

カテゴリ説明
ワークフローワークフローの送信、ステータスの確認
ジョブジョブのステータスとキューの監視
入力画像、マスク、その他の入力のアップロード
出力生成されたコンテンツのダウンロード
WebSocketリアルタイムの進捗更新
オブジェクト情報利用可能なノードとその定義

次のステップ

上記のクイックスタートでは、ワークフローの送信と結果の取得の基礎をカバーしています。より高度なユースケースについては、Cloud API リファレンスを参照してください:
  • 入力ファイルのアップロード - 外部入力を必要とするワークフローのために、画像、マスク、またはその他のユーザー提供コンテンツをアップロード
  • ワークフロー入力の修正 - 送信前にプロンプト、シード、またはノード設定などのワークフローパラメーターを動的に変更
  • パートナーノードの使用 - 追加の API キー設定を必要とする外部 AI サービス(Flux Pro、Ideogram など)を呼び出す
  • キュー管理 - キューのステータスの監視、ジョブのキャンセル、または実行中の実行の中断
  • エラー処理 - HTTP エラー、実行失敗の処理、および例外タイプの理解
追加リソース: