How To Call ComfyUI API with Python to Execute Workflows
2 min readHow To Execute Workflows via ComfyUI API Calls for stable diffusion? Pretty simple with a Python script. The example in this post can be found on this Gist. To call a workflow, simply export is as API format, then execute Python with the script and some parameters.
Quick Start to Execute a workflow via API Call
- Requisites: Get the script api_comfyui-img2img.py and save your workflow in API format.
python api_comfyui-img2img.py -w <path>\ComfyUI-workflow-recolor-api.json -i <path>\image-grey.jpg -o outputPrefix
Detailed Steps to execute a workflow via ComfyUI API Call
Pre-requisites:
- Install ComfyUI-Manager
cd ComfyUI\custom_nodes\ && git clone https://github.com/ltdrdata/ComfyUI-Manager
- Restart ComfyUI
- Install ComfyUI-Custom-Scripts:
- In the Manager, select Install Custom Nodes:
- Then search for Custom-Scripts and Install
- alternatively via command line:
cd ComfyUI\custom_nodes\ && git clone https://github.com/pythongosssss/ComfyUI-Custom-Scripts
- Restart ComfyUI
- In the Manager, select Install Custom Nodes:
- enable dev mode options:
- Build your workflow then save workflow in API format:
- execute
python api_comfyui-img2img.py -w <path>\ComfyUI-workflow-recolor-api.json -i <path>\image-grey.jpg -o outputPrefix
Saving the image outside the output folder is not allowed, that’s why the output is actually just a prefix
The ComfyUI API Calls Python script explained
# What really matters is the way we inject the workflow to the API # the workflow is JSON text coming from a file: prompt = json.load(file) # or a string: prompt = json.loads(prompt_text_example_1) # then we nest it under a "prompt" key: p = {"prompt": prompt} # then we encode it to UTF8: data = json.dumps(p).encode('utf-8') # then we create an http POST: req = urllib.request.Request(comfyUrl, data=data) with urllib.request.urlopen(req) as response: # Do stuff with complete data == wait for a reply. Unfortunately Comfy does not reply anything answer = response.read()
That’s it! ComfyUI will not wait after you inject the POST because of its queuing system. You can send many queries one after another and the files will generate in order.
Want to Call h2oGPT API instead?
Questions? Comments?