The ComfyUI API: Automating Image Generation
- Enable Dev Mode Options in ComfyUI and export a workflow in API format
- Explain the structure of the API format JSON and identify the node IDs for prompt text and seed
- Run the complete Python script to submit a workflow, wait for completion via WebSocket, and download the output images
- Modify the workflow object programmatically to generate variations and batch prompts
ComfyUI Is Already an API
Every time you click the Queue button in ComfyUI's interface, the browser is making an HTTP POST request to http://127.0.0.1:8188/prompt. The GUI is just a client for the server. That server has been running since ComfyUI started — no additional setup is required to begin using it programmatically.
This means you can submit workflows from a Python script, a web application, an n8n automation, or any tool that can make HTTP requests. The workflow you have already built in the ComfyUI interface is the same workflow you send to the API. There is no second format to learn, no deployment step — the server is running now on your machine.
Practical use cases:
- Batch generation: loop through a list of prompts or subjects and generate images for each without manual intervention
- Parameter sweeps: systematically test every combination of sampler, steps, and CFG values to find optimal settings
- Application backends: run ComfyUI on a GPU server and trigger generation from a web app or API endpoint
- Automation pipelines: connect ComfyUI to other tools — accept user input from a form, generate an image, deliver it to storage or email
Exporting a Workflow in API Format
ComfyUI stores workflow files in its own native format (nodes and links). The API uses a different format — a flat JSON object where each key is a node ID and the value is that node's configuration. You need the API format to submit workflows programmatically.
To export it:
- In ComfyUI, go to Settings (gear icon, top right) → Developer → enable Dev Mode Options.
- Return to the main canvas. A new option now appears when you open the workflow menu (the grid icon, top left): Save (API Format).
- Click Save (API Format). Save the file as
workflow_api.json.
Open the saved JSON in a text editor. You will see a structure like this:
{
"3": {
"inputs": {
"seed": 123456789,
"steps": 20,
"cfg": 1.0,
"sampler_name": "euler",
"scheduler": "simple",
"denoise": 1.0,
"model": ["4", 0],
"positive": ["6", 0],
"negative": ["7", 0],
"latent_image": ["5", 0]
},
"class_type": "KSampler",
"_meta": {"title": "KSampler"}
},
"6": {
"inputs": {
"text": "a photorealistic portrait of a woman",
"clip": ["4", 1]
},
"class_type": "CLIPTextEncode",
"_meta": {"title": "CLIP Text Encode (Positive)"}
}
}
Each node has a numeric string ID. The inputs object contains either direct values (like "seed": 123456789) or references to another node's output (like ["4", 0], meaning node 4's first output). To change the prompt via the API, you change the text value inside the CLIPTextEncode node's inputs. To change the seed, you change the seed value inside the KSampler node's inputs.
The Complete API Script
The following Python script submits a workflow from workflow_api.json, waits for completion using a WebSocket connection, and downloads all generated images. It uses only Python standard library modules plus the websocket-client package (pip install websocket-client).
import json
import uuid
import urllib.parse
import urllib.request
import websocket # pip install websocket-client
SERVER = "127.0.0.1:8188"
CLIENT_ID = str(uuid.uuid4())
def queue_prompt(prompt, prompt_id):
body = json.dumps({
"prompt": prompt,
"client_id": CLIENT_ID,
"prompt_id": prompt_id,
}).encode("utf-8")
req = urllib.request.Request(
f"http://{SERVER}/prompt",
data=body,
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(req) as resp:
return json.loads(resp.read())
def wait_for_completion(ws, prompt_id):
while True:
msg = ws.recv()
if isinstance(msg, str):
data = json.loads(msg)
if data["type"] == "executing":
d = data["data"]
if d["node"] is None and d["prompt_id"] == prompt_id:
return
def get_history(prompt_id):
with urllib.request.urlopen(
f"http://{SERVER}/history/{prompt_id}"
) as resp:
return json.loads(resp.read())[prompt_id]
def download_image(filename, subfolder, folder_type):
params = urllib.parse.urlencode({
"filename": filename,
"subfolder": subfolder,
"type": folder_type,
})
with urllib.request.urlopen(f"http://{SERVER}/view?{params}") as resp:
return resp.read()
if __name__ == "__main__":
with open("workflow_api.json") as f:
workflow = json.load(f)
prompt_id = str(uuid.uuid4())
ws = websocket.WebSocket()
ws.connect(f"ws://{SERVER}/ws?clientId={CLIENT_ID}")
queue_prompt(workflow, prompt_id)
wait_for_completion(ws, prompt_id)
ws.close()
outputs = get_history(prompt_id)["outputs"]
for node_id, node_output in outputs.items():
for img in node_output.get("images", []):
data = download_image(
img["filename"], img["subfolder"], img["type"]
)
with open(img["filename"], "wb") as f:
f.write(data)
print(f"Saved {img['filename']}")
Run it: python generate.py. The script connects the WebSocket before queuing so no completion messages are missed, submits the workflow, waits silently until ComfyUI signals it is done, then downloads and saves every image the workflow produced.
Modifying the Workflow Programmatically
To generate different images without touching the JSON file each time, modify the workflow object in Python before submitting it. First, identify the node IDs for the values you want to change by opening workflow_api.json and finding the relevant nodes. Then overwrite their input values in the script:
with open("workflow_api.json") as f:
workflow = json.load(f)
# Change the prompt text (node "6" is the positive CLIP Text Encode)
workflow["6"]["inputs"]["text"] = "a woman in a red jacket"
# Randomise the seed for each run
import random
workflow["3"]["inputs"]["seed"] = random.randint(0, 2**32)
queue_prompt(workflow, prompt_id)
For batch generation, wrap this in a loop:
prompts = [
"a woman in a red jacket",
"a man wearing a blue coat",
"a child on a bicycle",
]
for prompt_text in prompts:
workflow["6"]["inputs"]["text"] = prompt_text
workflow["3"]["inputs"]["seed"] = random.randint(0, 2**32)
prompt_id = str(uuid.uuid4())
queue_prompt(workflow, prompt_id)
wait_for_completion(ws, prompt_id)
# download images here
Important API Endpoints
Beyond /prompt, the ComfyUI server exposes several useful endpoints:
- GET /history — returns the generation history for all recent prompts
- GET /history/{prompt_id} — returns the execution record for a specific prompt, including output file information
- GET /view?filename=X&subfolder=Y&type=Z — downloads a generated file; the filename, subfolder, and type come from the history response
- GET /queue — returns the current queue state (pending and running prompts)
- POST /interrupt — cancels the currently running generation
- GET /system_stats — returns GPU usage, VRAM status, and other system information
These endpoints are unauthenticated by default — anyone who can reach port 8188 can submit prompts and read outputs. When running ComfyUI on a remote server accessible from the internet, place it behind a reverse proxy with authentication. When running locally (the default), no additional security is needed.
Remote Access
ComfyUI binds to 127.0.0.1 (localhost) by default, which means only the machine itself can reach the API. To allow access from another machine:
- SSH port forwarding (most secure):
ssh -L 8188:localhost:8188 user@server— tunnels the remote port to your local machine. Access it athttp://localhost:8188on your machine. No firewall changes needed. - Listen on all interfaces: start ComfyUI with
--listen 0.0.0.0. The API is then reachable athttp://SERVER_IP:8188. Only use this in a trusted network environment — the API has no authentication.
Lesson 10 builds on this foundation with a FastAPI wrapper that adds an authenticated endpoint, error handling, and queue management — turning ComfyUI into a proper backend service you can call from web applications or n8n automations.
- ComfyUI starts an HTTP API server at port 8188 automatically — no additional setup is required; the Queue button in the GUI is making the same POST /prompt request your Python script will make
- API format JSON is different from the native workflow format — export it via Settings → Developer → Dev Mode Options → Save (API Format)
- The WebSocket channel at /ws is the correct way to wait for completion — connect it before queuing so no executing messages are missed
- To generate variations programmatically, load workflow_api.json in Python, modify the inputs value on the target node directly (prompt text, seed), then call queue_prompt — no need to edit the JSON file each time
- The /prompt, /history, and /view endpoints cover the full generation cycle; /queue and /interrupt let you manage what is running
Progress is saved in this browser only — clear your cache or switch device and it's gone. Create a free account and it follows you everywhere.