ComfyUI 原生 REST API 技术文档
2025-08-22 版
仓库:https://github.com/comfyanonymous/ComfyUI
协议:GPL-3.0
0 元数据
项 | 值 |
---|---|
文档版本 | v1.4 |
适用 ComfyUI 版本 | ≥ 2024-12 |
字符编码 | UTF-8 / LF |
示例 Host | http://127.0.0.1:8188 |
1 启动与前置条件
-
安装
git clone https://github.com/comfyanonymous/ComfyUI.git cd ComfyUI pip install -r requirements.txt
-
无 UI 启动(仅 API)
python main.py --listen 0.0.0.0 --port 8188 --disable-auto-launch
可选参数:
--api-key myKey
→ 开启 Bearer Token 鉴权--enable-cors-header
→ 允许浏览器跨域--verbose
→ 输出 HTTP 日志
-
健康检查
curl -s http://localhost:8188/system_stats | jq .
返回系统信息即表示 API 就绪。
2 通用约定
名称 | 说明 |
---|---|
client_id | 任意字符串,用于 WebSocket 路由;建议 UUID v4 |
prompt | 完整的 workflow JSON;键为节点编号,值为节点对象 |
分页 | 无。/history 默认返回全部记录,量大时自行过滤 |
错误格式 | {"error": "<msg>", "node_errors": {...}} |
图片路径规则 | type ∈ {input , output , temp };subfolder 可空 |
3 任务接口详解
3.1 POST /prompt
—— 提交任务
请求
POST /prompt HTTP/1.1
Content-Type: application/json
Authorization: Bearer <key> # 若启用
{"client_id": "a1b2c3","prompt": {"3": {"inputs": {"seed": 42,"steps": 20,"cfg": 8,"sampler_name": "euler","scheduler": "normal","denoise": 1,"model": ["4", 0],"positive": ["6", 0],"negative": ["7", 0],"latent_image": ["5", 0]},"class_type": "KSampler"},...},"extra_data": {"extra_pnginfo": { "workflow": {...} }},"number": 0 // 可选,插入到队列位置
}
响应
{"prompt_id": "uuid-here","number": 5,"node_errors": {}
}
3.2 GET /queue
—— 查看队列
curl http://localhost:8188/queue
{"queue_running": [{"prompt_id": "id1", "prompt": {...}, "extra_data": {...}}],"queue_pending": [{"prompt_id": "id2", "prompt": {...}}]
}
3.3 GET /history/{prompt_id}
—— 单条历史
curl http://localhost:8188/history/uuid-here
返回结构:
{"uuid-here": {"prompt": [ ... ],"outputs": {"9": {"images": [{"filename": "ComfyUI_00001_.png","subfolder": "","type": "output"}]}},"status": {"status_str": "success","completed": true,"messages": [...]}}
}
3.4 DELETE /prompt/{prompt_id}
—— 取消任务
curl -X DELETE http://localhost:8188/prompt/uuid-here
成功返回 HTTP 204 No Content
。
4 文件 / 图片接口
4.1 POST /upload/image
curl -F "image=@girl.png" \-F "subfolder=sdxl" \http://localhost:8188/upload/image
返回
{"name": "girl.png", "subfolder": "sdxl", "type": "input"}
4.2 GET /view
curl "http://localhost:8188/view?filename=ComfyUI_00001_.png&type=output" \-o 00001.png
可选参数:
format=webp
即时转码quality=80
WebP 质量
4.3 GET /view_metadata/{filename}?type=output
返回 PNG 的 tEXt
块解析结果,内含完整 prompt 与 workflow。
5 系统接口
5.1 GET /system_stats
{"system": {"os": "Linux","python_version": "3.11.9","pytorch_version": "2.3.0+cu121"},"devices": [{"name": "NVIDIA GeForce RTX 4090","type": "cuda","index": 0,"vram_total": 25756696576,"vram_free": 20234186752}]
}
5.2 GET /object_info
返回所有节点 schema,可用于动态 UI 生成。
5.3 GET /embeddings
["EasyNegative.pt", "FastNegativeEmbedding.pt"]
5.4 GET /extensions
["ComfyUI-Manager", "ComfyUI-Impact-Pack"]
6 WebSocket 实时通道
6.1 建立连接
ws://localhost:8188/ws?clientId=a1b2c3
Headers(若启用 API Key):
Authorization: Bearer myKey
6.2 事件一览
事件类型 | 示例 payload | 触发时机 |
---|---|---|
status | {"type": "status", "data": {"status_str": "success", "completed": false}} | 任务整体状态变化 |
executing | {"type": "executing", "data": {"node": "3"}} | 开始执行某个节点 |
progress | {"type": "progress", "data": {"value": 12, "max": 20}} | 采样步骤进度 |
executed | {"type": "executed", "data": {"node": "9", "output": {"images":[...]}}} | 节点完成 |
execution_error | 含 exception_message | 节点异常 |
7 时序图(Mermaid)
8 多语言示例
8.1 Python (同步)
import requests, json, uuid
host = "http://localhost:8188"
client_id = str(uuid.uuid4())# 1. 提交
prompt = json.load(open("workflow_api.json"))
r = requests.post(f"{host}/prompt", json={"client_id": client_id, "prompt": prompt})
pid = r.json()["prompt_id"]# 2. 下载
import websocket, io
from PIL import Imagedef on_message(ws, msg):m = json.loads(msg)if m["type"] == "executed":for img in m["data"]["output"]["images"]:url = f"{host}/view?filename={img['filename']}&type={img['type']}"img_bin = requests.get(url).contentImage.open(io.BytesIO(img_bin)).save(img["filename"])ws = websocket.WebSocketApp(f"ws://localhost:8188/ws?clientId={client_id}",on_message=on_message)
ws.run_forever()
8.2 JavaScript (浏览器)
const host = "http://localhost:8188";
const clientId = crypto.randomUUID();fetch(`${host}/prompt`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ client_id: clientId, prompt: workflow })
});const ws = new WebSocket(`ws://localhost:8188/ws?clientId=${clientId}`);
ws.onmessage = (e) => {const msg = JSON.parse(e.data);if (msg.type === "executed") {const img = msg.data.output.images[0];const url = `${host}/view?filename=${img.filename}&type=${img.type}`;document.body.insertAdjacentHTML("beforeend", `<img src="${url}">`);}
};
9 常见陷阱 & 调试
现象 | 原因 & 解决 |
---|---|
401 Unauthorized | 忘记加 Header Authorization: Bearer <key> |
422 Unprocessable Entity | prompt JSON 节点编号不连续或缺失输入 |
图片返回 404 | type 拼写错误,实际应为 output |
WebSocket 无消息 | client_id 与提交时不一致 |
显存不足 | 先 GET /system_stats 查看 vram_free ,再降低 batch |
10 FAQ
Q1:如何分页拉取历史?
A:目前无分页参数,建议本地缓存 prompt_id
,定期 DELETE /history/{id}
清理。
Q2:能一次性上传多张图吗?
A:/upload/image
仅支持单文件;多图需循环调用,或使用 zip 后自行解压节点。
Q3:如何获取进度条百分比?
A:监听 WebSocket progress
事件,计算 value / max * 100
。
Q4:是否支持 HTTPS?
A:官方未内置。可在 Nginx 反向代理中配置 SSL。
11 附录
- ComfyUI CLI 参数全表