# ImageLab External API Documentation **Version:** 1.0 **Base URL:** `http://127.0.0.1:8188` **Purpose:** This document serves as a complete reference for the ImageLab External API and relevant ComfyUI endpoints. Use this as a steering document for frontend development. --- ## Table of Contents 1. [Architecture Overview](#architecture-overview) 2. [ImageLab API Endpoints](#imagelab-api-endpoints) 3. [ComfyUI API Endpoints](#comfyui-api-endpoints) 4. [WebSocket System](#websocket-system) 5. [Binary Events](#binary-events) 6. [JavaScript Examples](#javascript-examples) 7. [Core Systems](#core-systems) --- ## Architecture Overview The ImageLab External API extends ComfyUI with: - **Workflow Management**: Execute ComfyScript-based workflows via REST API - **Resource Discovery**: List and index models with metadata (hash, CivitAI info) - **Progress Monitoring**: Real-time progress updates via WebSocket binary events - **Hot Reloading**: Workflows reload from disk on each execution for development ### Technology Stack - **Server**: ComfyUI (aiohttp web server) - **Workflow Engine**: ComfyScript (Python runtime for ComfyUI) - **Validation**: Pydantic (parameter validation) - **Communication**: REST + WebSocket (JSON and Binary) --- ## ImageLab API Endpoints ### Workflow Endpoints #### `GET /imagelab/workflows` List all available workflows with metadata. **Response Type:** `application/json` **Response Schema:** ```json { "workflows": [ { "id": "test_workflow", "name": "Test Workflow", "description": "Simple test workflow for image generation", "model_types": ["SDXL", "Pony", "Illustrious"], "category": "Image Generation" } ] } ``` **JavaScript Example:** ```javascript const response = await fetch("http://127.0.0.1:8188/imagelab/workflows"); const { workflows } = await response.json(); console.log("Available workflows:", workflows); ``` --- #### `GET /imagelab/workflow/{workflow_name}/metadata` Get metadata for a specific workflow. **Parameters:** - `workflow_name` (path): Workflow identifier **Response Type:** `application/json` **Response Schema:** ```json { "success": true, "workflow": "test_workflow", "metadata": { "name": "Test Workflow", "description": "Simple test workflow for image generation", "model_types": ["SDXL", "Pony", "Illustrious"], "category": "generation" } } ``` **JavaScript Example:** ```javascript const response = await fetch( "http://127.0.0.1:8188/imagelab/workflow/test_workflow/metadata" ); const { metadata } = await response.json(); console.log("Workflow info:", metadata); ``` --- #### `POST /imagelab/workflow/{workflow_name}` Execute a workflow with parameters. **Parameters:** - `workflow_name` (path): Workflow identifier **Request Type:** `application/json` **Request Body:** Varies by workflow. Example: ```json { "prompt": "a beautiful sunset over mountains", "negativePrompt": "blurry, low quality", "checkpoints": ["model.safetensors"], "loras": [ { "apiName": "detail_enhancer.safetensors", "disabled": false, "parameters": { "strength_model": 1.0, "strength_clip": 1.0 } } ], "steps": 20, "seed": 42, "width": 512, "height": 512 } ``` **Response Type:** `application/json` **Response Schema:** ```json { "success": true, "workflow": "test_workflow", "result": { "prompt_id": "abc123-def456-...", "status": "queued", "parameters": { /* echo of input parameters */ } } } ``` **Error Response:** ```json { "success": false, "type": "ValueError", "error": "Workflow 'invalid_name' not found. Available: ['test_workflow']" } ``` **JavaScript Example:** ```javascript const response = await fetch( "http://127.0.0.1:8188/imagelab/workflow/test_workflow", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt: "a serene landscape", checkpoints: ["dreamshaper_8.safetensors"], steps: 20, seed: Math.floor(Math.random() * 1000000), }), } ); const { result } = await response.json(); console.log("Workflow queued with prompt_id:", result.prompt_id); ``` --- ### Resource Endpoints #### `GET /imagelab/resources` Get all available resources (models, samplers, schedulers). **Response Type:** `application/json` **Response Schema:** ```json { "success": true, "resources": { "checkpoints": [ { "label": "dreamshaper_8", "apiName": "dreamshaper_8.safetensors", "indexed": true } ], "loras": [ /* ... */ ], "samplers": [{ "label": "euler", "apiName": "euler", "metadata": null }], "schedulers": [ { "label": "normal", "apiName": "normal", "metadata": null } ], "upscale_methods": [ /* ... */ ] } } ``` **JavaScript Example:** ```javascript const response = await fetch("http://127.0.0.1:8188/imagelab/resources"); const { resources } = await response.json(); // Build dropdown for checkpoints const checkpointSelect = document.getElementById("checkpoint-select"); resources.checkpoints.forEach((model) => { const option = document.createElement("option"); option.value = model.apiName; option.textContent = model.label; if (model.indexed) { option.textContent += " ✓"; // Indicates metadata available } checkpointSelect.appendChild(option); }); ``` --- #### `GET /imagelab/resources/{resource_type}` Get resources of a specific type. **Parameters:** - `resource_type` (path): Type of resource (`checkpoints`, `loras`, `vae`, `samplers`, `schedulers`, `upscale_methods`, etc.) **Response Type:** `application/json` **Response Schema:** ```json { "success": true, "resource_type": "loras", "items": [ { "label": "add_detail", "apiName": "add_detail.safetensors", "indexed": false } ] } ``` **JavaScript Example:** ```javascript const response = await fetch("http://127.0.0.1:8188/imagelab/resources/loras"); const { items } = await response.json(); console.log("Available LoRAs:", items); ``` --- #### `POST /imagelab/resources/{resource_type}/index/{filename}` Index a specific model file to calculate hash and fetch metadata. **Parameters:** - `resource_type` (path): Type of resource (`checkpoints`, `loras`, etc.) - `filename` (path): Exact filename including extension **Response Type:** `application/json` **Response Schema:** ```json { "success": true, "resource_type": "checkpoints", "filename": "dreamshaper_8.safetensors", "metadata": { "filename": "dreamshaper_8.safetensors", "hash": "9aba26abdf...", "civitai": { "id": 12345, "name": "DreamShaper 8", "description": "...", "images": [ /* preview images */ ] }, "imagelab": {} } } ``` **JavaScript Example:** ```javascript // Index a model when user requests metadata async function indexModel(type, filename) { const response = await fetch( `http://127.0.0.1:8188/imagelab/resources/${type}/index/${encodeURIComponent(filename)}`, { method: "POST" } ); const { metadata } = await response.json(); // Display CivitAI info if (metadata.civitai) { console.log("Model info:", metadata.civitai.name); console.log("Preview:", metadata.civitai.images[0]?.url); } return metadata; } // Usage await indexModel("checkpoints", "dreamshaper_8.safetensors"); ``` --- #### `POST /imagelab/resources/index-all` Index all models that don't have index files yet. Returns count of indexed models per type. **Response Type:** `application/json` **Response Schema:** ```json { "success": true, "message": "Indexing complete", "indexed": { "checkpoints": 5, "loras": 12, "vae": 2 } } ``` **JavaScript Example:** ```javascript // Trigger bulk indexing (long-running operation) async function indexAllModels() { const response = await fetch( "http://127.0.0.1:8188/imagelab/resources/index-all", { method: "POST", } ); const { indexed } = await response.json(); console.log("Indexed models:", indexed); } ``` --- ## ComfyUI API Endpoints These are the core ComfyUI endpoints you'll use alongside ImageLab endpoints. ### Model Discovery #### `GET /models` List all model types available in ComfyUI. **Response Type:** `application/json` **Response:** Array of model type strings ```json ["checkpoints", "loras", "vae", "embeddings", "controlnet", ...] ``` --- #### `GET /models/{folder}` Get filenames for a specific model type. **Parameters:** - `folder` (path): Model type (`checkpoints`, `loras`, etc.) **Response Type:** `application/json` **Response:** Array of filenames ```json ["model1.safetensors", "model2.ckpt", ...] ``` **JavaScript Example:** ```javascript // Get all checkpoints const response = await fetch("http://127.0.0.1:8188/models/checkpoints"); const checkpoints = await response.json(); console.log("Checkpoints:", checkpoints); ``` --- ### Image Viewing #### `GET /view?filename={filename}&type={type}&subfolder={subfolder}` View/download generated images. **Parameters:** - `filename` (query): Image filename - `type` (query): Directory type (`output`, `input`, `temp`) - `subfolder` (query, optional): Subdirectory path - `preview` (query, optional): Format and quality (e.g., `jpeg;80`) - `channel` (query, optional): Color channel (`rgb`, `rgba`, `a`) **Response Type:** `image/*` or file download **JavaScript Example:** ```javascript // Display generated image const imageUrl = `http://127.0.0.1:8188/view?filename=ComfyUI_00001.png&type=output`; document.getElementById("result-img").src = imageUrl; // Get preview (smaller, compressed) const previewUrl = `http://127.0.0.1:8188/view?filename=ComfyUI_00001.png&type=output&preview=jpeg;80`; ``` --- ### Queue Management #### `GET /queue` Get current queue status. **Response Type:** `application/json` **Response Schema:** ```json { "queue_running": [ [ 1, "prompt_id", { /* prompt */ }, { /* extra_data */ }, [] ] ], "queue_pending": [] } ``` --- #### `POST /queue` Modify the queue (clear or delete items). **Request Type:** `application/json` **Request Body:** ```json { "clear": true // Clear all pending items } ``` or ```json { "delete": ["prompt_id1", "prompt_id2"] // Delete specific items } ``` **JavaScript Example:** ```javascript // Clear the queue await fetch("http://127.0.0.1:8188/queue", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ clear: true }), }); ``` --- #### `POST /interrupt` Interrupt current execution. **Request Type:** `application/json` (optional) **Request Body (optional):** ```json { "prompt_id": "abc123" // Interrupt specific prompt } ``` **JavaScript Example:** ```javascript // Interrupt all await fetch("http://127.0.0.1:8188/interrupt", { method: "POST" }); // Interrupt specific prompt await fetch("http://127.0.0.1:8188/interrupt", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt_id: currentPromptId }), }); ``` --- ### History #### `GET /history` Get execution history. **Query Parameters:** - `max_items` (optional): Maximum items to return - `offset` (optional): Pagination offset **Response Type:** `application/json` **Response:** Object with prompt IDs as keys ```json { "prompt_id_1": { "prompt": [ /* nodes */ ], "outputs": { /* output data */ }, "status": { /* execution status */ } } } ``` --- #### `GET /history/{prompt_id}` Get history for a specific prompt. **Parameters:** - `prompt_id` (path): Prompt identifier **Response Type:** `application/json` --- ### System Info #### `GET /system_stats` Get system information (RAM, VRAM, versions). **Response Type:** `application/json` **Response Schema:** ```json { "system": { "os": "win32", "ram_total": 34359738368, "ram_free": 12884901888, "comfyui_version": "1.0.0", "python_version": "3.12.0", "pytorch_version": "2.1.0" }, "devices": [ { "name": "NVIDIA GeForce RTX 4090", "type": "cuda", "index": 0, "vram_total": 25769803776, "vram_free": 20000000000 } ] } ``` **JavaScript Example:** ```javascript const response = await fetch("http://127.0.0.1:8188/system_stats"); const { system, devices } = await response.json(); console.log(`VRAM: ${devices[0].vram_free / 1024 / 1024 / 1024} GB free`); console.log(`RAM: ${system.ram_free / 1024 / 1024 / 1024} GB free`); ``` --- ## WebSocket System ### Connection **Endpoint:** `ws://127.0.0.1:8188/ws` **Optional Query Parameter:** `?clientId=your_client_id` ComfyUI's WebSocket supports both JSON text messages and binary messages. ### Message Types #### JSON Messages (from ComfyUI) - `status`: Queue status updates - `executing`: Currently executing node - `executed`: Node execution completed - `execution_start`: Workflow execution started - `execution_cached`: Nodes that were cached - `execution_error`: Error during execution - `progress`: Execution progress (deprecated, use binary events) #### Binary Messages (from ImageLab) - **Event 100**: `IMAGELAB_PROGRESS_EVENT` - Progress data (JSON) - **Event 101**: `IMAGELAB_PREVIEW_EVENT` - Preview image (binary) ### JavaScript WebSocket Client ```javascript class ComfyUIClient { constructor(serverUrl = "ws://127.0.0.1:8188/ws") { this.ws = null; this.serverUrl = serverUrl; this.handlers = { progress: [], preview: [], status: [], executed: [], }; } connect() { return new Promise((resolve, reject) => { this.ws = new WebSocket(this.serverUrl); this.ws.onopen = () => { console.log("Connected to ComfyUI"); resolve(); }; this.ws.onerror = (error) => { console.error("WebSocket error:", error); reject(error); }; this.ws.onmessage = (event) => { if (event.data instanceof Blob) { this.handleBinaryMessage(event.data); } else { const message = JSON.parse(event.data); this.handleJsonMessage(message); } }; }); } handleBinaryMessage(blob) { blob.arrayBuffer().then((buffer) => { const view = new DataView(buffer); const eventType = view.getUint32(0); // First 4 bytes = event type const payload = buffer.slice(4); if (eventType === 100) { // IMAGELAB_PROGRESS_EVENT const decoder = new TextDecoder(); const jsonString = decoder.decode(payload); const progressData = JSON.parse(jsonString); this.emit("progress", progressData); } else if (eventType === 101) { // IMAGELAB_PREVIEW_EVENT const blob = new Blob([payload], { type: "image/jpeg" }); const imageUrl = URL.createObjectURL(blob); this.emit("preview", imageUrl); } }); } handleJsonMessage(message) { const { type, data } = message; this.emit(type, data); } on(event, handler) { if (!this.handlers[event]) { this.handlers[event] = []; } this.handlers[event].push(handler); } emit(event, data) { if (this.handlers[event]) { this.handlers[event].forEach((handler) => handler(data)); } } disconnect() { if (this.ws) { this.ws.close(); } } } // Usage const client = new ComfyUIClient(); await client.connect(); // Listen for progress updates client.on("progress", (data) => { console.log(`Progress: ${data.progress_percent}%`); updateProgressBar(data.progress_percent); }); // Listen for preview images client.on("preview", (imageUrl) => { document.getElementById("preview-img").src = imageUrl; }); // Listen for completion client.on("executed", (data) => { console.log("Node executed:", data); }); client.on("status", (data) => { console.log("Queue status:", data.status); }); ``` --- ## Binary Events ### Event 100: IMAGELAB_PROGRESS_EVENT **Structure:** ``` [4 bytes: event type (100)] [remaining bytes: JSON as UTF-8] ``` **JSON Payload:** ```json { "value": 5, "total": 20, "prompt_id": "abc123-def456-...", "node_id": "KSampler.0", "progress_percent": 25.0 } ``` **JavaScript Parsing:** ```javascript // In handleBinaryMessage if (eventType === 100) { const decoder = new TextDecoder("utf-8"); const jsonString = decoder.decode(payload); const progress = JSON.parse(jsonString); console.log( `${progress.value}/${progress.total} (${progress.progress_percent}%)` ); } ``` --- ### Event 101: IMAGELAB_PREVIEW_EVENT **Structure:** ``` [4 bytes: event type (101)] [remaining bytes: image data (JPEG or PNG)] ``` **JavaScript Parsing:** ```javascript // In handleBinaryMessage if (eventType === 101) { // Create a blob from the raw image data const imageBlob = new Blob([payload], { type: "image/jpeg" }); // Create object URL for display const imageUrl = URL.createObjectURL(imageBlob); // Display in img element document.getElementById("preview").src = imageUrl; // Don't forget to revoke when done // URL.revokeObjectURL(imageUrl); } ``` --- ## JavaScript Examples ### Complete Workflow Execution Example ```javascript class ImageLabClient { constructor() { this.baseUrl = "http://127.0.0.1:8188"; this.ws = null; } async executeWorkflow(workflowName, parameters) { // 1. Connect WebSocket for progress monitoring await this.connectWebSocket(); // 2. Execute workflow const response = await fetch( `${this.baseUrl}/imagelab/workflow/${workflowName}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(parameters), } ); const { result } = await response.json(); console.log("Workflow started:", result.prompt_id); return result.prompt_id; } async connectWebSocket() { return new Promise((resolve, reject) => { this.ws = new WebSocket("ws://127.0.0.1:8188/ws"); this.ws.onopen = () => resolve(); this.ws.onerror = reject; this.ws.onmessage = (event) => { if (event.data instanceof Blob) { this.handleBinaryMessage(event.data); } else { const message = JSON.parse(event.data); if (message.type === "executed") { this.onWorkflowComplete(message.data); } } }; }); } handleBinaryMessage(blob) { blob.arrayBuffer().then((buffer) => { const view = new DataView(buffer); const eventType = view.getUint32(0); const payload = buffer.slice(4); if (eventType === 100) { // Progress const decoder = new TextDecoder(); const progress = JSON.parse(decoder.decode(payload)); this.onProgress(progress); } else if (eventType === 101) { // Preview image const imageUrl = URL.createObjectURL( new Blob([payload], { type: "image/jpeg" }) ); this.onPreview(imageUrl); } }); } onProgress(data) { console.log(`Progress: ${data.progress_percent}%`); // Update UI document.getElementById("progress-bar").style.width = `${data.progress_percent}%`; document.getElementById("progress-text").textContent = `${data.value}/${data.total} steps`; } onPreview(imageUrl) { document.getElementById("preview-image").src = imageUrl; } onWorkflowComplete(data) { console.log("Workflow complete!", data); // Fetch final output images this.displayOutputs(data); } async displayOutputs(executionData) { // Parse output data to get image filenames const outputs = executionData.output; for (const nodeId in outputs) { const output = outputs[nodeId]; if (output.images) { output.images.forEach((img) => { const imageUrl = `${this.baseUrl}/view?filename=${img.filename}&type=${img.type}&subfolder=${img.subfolder || ""}`; // Display image const imgElement = document.createElement("img"); imgElement.src = imageUrl; document.getElementById("output-gallery").appendChild(imgElement); }); } } } } // Usage const client = new ImageLabClient(); await client.executeWorkflow("test_workflow", { prompt: "a beautiful sunset over mountains, highly detailed", negativePrompt: "blurry, low quality, watermark", checkpoints: ["dreamshaper_8.safetensors"], loras: [ { apiName: "add_detail.safetensors", disabled: false, parameters: { strength_model: 0.8, strength_clip: 0.8 }, }, ], steps: 20, seed: Math.floor(Math.random() * 1000000), width: 512, height: 512, }); ``` --- ### Resource Management Example ```javascript class ResourceManager { constructor(baseUrl = "http://127.0.0.1:8188") { this.baseUrl = baseUrl; this.cache = { resources: null, metadata: new Map(), }; } async loadAllResources() { const response = await fetch(`${this.baseUrl}/imagelab/resources`); const { resources } = await response.json(); this.cache.resources = resources; return resources; } async loadResourceType(type) { const response = await fetch(`${this.baseUrl}/imagelab/resources/${type}`); const { items } = await response.json(); return items; } async getModelMetadata(type, filename) { // Check cache first const cacheKey = `${type}:${filename}`; if (this.cache.metadata.has(cacheKey)) { return this.cache.metadata.get(cacheKey); } // Fetch and index const response = await fetch( `${this.baseUrl}/imagelab/resources/${type}/index/${encodeURIComponent(filename)}`, { method: "POST" } ); const { metadata } = await response.json(); // Cache result this.cache.metadata.set(cacheKey, metadata); return metadata; } async indexAllModels() { const response = await fetch( `${this.baseUrl}/imagelab/resources/index-all`, { method: "POST", } ); return await response.json(); } // Build UI dropdowns async populateCheckpointSelector(selectElement) { const checkpoints = await this.loadResourceType("checkpoints"); selectElement.innerHTML = ""; checkpoints.forEach((model) => { const option = document.createElement("option"); option.value = model.apiName; option.textContent = model.label; option.dataset.indexed = model.indexed; selectElement.appendChild(option); }); } // Show model info on hover/click async showModelInfo(type, filename, targetElement) { const metadata = await this.getModelMetadata(type, filename); if (metadata.civitai) { targetElement.innerHTML = `
${metadata.civitai.description}
${ metadata.civitai.images && metadata.civitai.images[0] ? `