当前位置: 首页 > news >正文

ComfyUI 原生 REST API 技术文档

2025-08-22 版
仓库:https://github.com/comfyanonymous/ComfyUI
协议:GPL-3.0


0 元数据

文档版本v1.4
适用 ComfyUI 版本≥ 2024-12
字符编码UTF-8 / LF
示例 Hosthttp://127.0.0.1:8188

1 启动与前置条件

  1. 安装

    git clone https://github.com/comfyanonymous/ComfyUI.git
    cd ComfyUI
    pip install -r requirements.txt
    
  2. 无 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 日志
  3. 健康检查

    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_errorexception_message节点异常

7 时序图(Mermaid)

ClientComfyUI RESTWebSocketGET /object_info节点 schemaPOST /promptprompt_idconnect /ws?clientId=xxx{"type":"progress",...}loop[每步]{"type":"executed","data":{...}}GET /view?filename=...图片二进制ClientComfyUI RESTWebSocket

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 Entityprompt JSON 节点编号不连续或缺失输入
图片返回 404type 拼写错误,实际应为 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 参数全表
http://www.dtcms.com/a/345088.html

相关文章:

  • 视频拼接融合技术:打造全景视界的革命性产品
  • modbus绑定变量,并发送8位数据的办法
  • Vue中的methods 和 computed
  • Linux-Makefile
  • 网络编程6(JVM)
  • 【Redis】哨兵模式和集群模式
  • 红帽认证升级华为openEuler证书活动!
  • 【学习记录】c完整线程池实现
  • 未来已来?AI 预测技术在气象、金融领域的应用现状与风险警示
  • MySQL视图详解:从基础概念到实战案例
  • 人工智能-python-深度学习-软件安装阶段
  • 第2章 cmd命令基础:执行动态链接库(rundll32)
  • 大视协作码垛机器人:定制圆形吸盘破解桶型码垛难题
  • HEVC(H.265)与HVC1的关系及区别
  • 【C初阶】数据在内存中的存储
  • 【LeetCode 热题 100】139. 单词拆分——(解法一)记忆化搜索
  • Vue 插槽(Slots)全解析1
  • 所做过的笔试真题
  • 阿里云RDS MySQL数据归档全攻略:方案选择指南
  • (LeetCode 面试经典 150 题) 124. 二叉树中的最大路径和 (深度优先搜索dfs)
  • 大麦盒子DM4036刷包推荐
  • 停车场道闸的常见形式
  • 【会议跟踪】Model-Based Systems Engineering (MBSE) in Practice 2025
  • 场景题:内存溢出 和 内存泄漏 有啥区别?
  • Python-UV
  • Android夜间模式切换及自定义夜间模式切换按钮实现快速适配夜间模式
  • LeetCode Hot 100 第一天
  • 《器件在EMC中的应用》---TVS在EMC中的应用
  • 中国大学MOOC--C语言第十一周结构类型
  • 开源版CRM客户关系管理系统源码包+搭建部署教程