Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:AUTOMATIC1111 Stable diffusion webui API Server

From Leeroopedia
Revision as of 14:02, 16 February 2026 by Admin (talk | contribs) (Auto-imported from implementations/AUTOMATIC1111_Stable_diffusion_webui_API_Server.md)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


Knowledge Sources
Domains API, REST, Image Generation
Last Updated 2025-05-15 00:00 GMT

Overview

Implements the REST API server for Stable Diffusion WebUI, exposing all core image generation, model management, and configuration functionality as HTTP endpoints under the /sdapi/v1/ path.

Description

The Api class is the central API server built on FastAPI. It registers over 30 routes covering the full feature set:

Image generation: /sdapi/v1/txt2img (POST) and /sdapi/v1/img2img (POST) accept processing parameters, handle script initialization, infotext parsing, sampler/scheduler resolution, and execute the generation pipeline with queue locking. Results are returned as base64-encoded images.

Post-processing: /sdapi/v1/extra-single-image and /sdapi/v1/extra-batch-images handle upscaling and face restoration via the extras pipeline.

Model management: Endpoints for listing and refreshing models (/sdapi/v1/sd-models), VAEs (/sdapi/v1/sd-vae), samplers, schedulers, upscalers, hypernetworks, embeddings, and face restorers. Also includes /sdapi/v1/unload-checkpoint and /sdapi/v1/reload-checkpoint.

Configuration: /sdapi/v1/options (GET/POST) for reading and updating settings, /sdapi/v1/cmd-flags for command-line flags.

Training: Endpoints for creating and training embeddings and hypernetworks.

Utilities: Progress tracking, PNG info extraction, CLIP/DeepBooru interrogation, script listing, and extension information.

Helper functions provide: base64 image encoding/decoding with format support (PNG, JPEG, WebP), URL verification for SSRF protection (verify_url), sampler name validation, request logging middleware with timing, and comprehensive error handling with optional Rich console output. Authentication is supported via HTTP Basic credentials from the --api-auth command-line flag.

Usage

The API server is initialized when the WebUI starts with the --api flag. External tools, scripts, and integrations can send HTTP requests to generate images and manage settings without using the Gradio UI. Full OpenAPI documentation is available at /docs.

Code Reference

Source Location

Signature

class Api:
    def __init__(self, app: FastAPI, queue_lock: Lock): ...
    def add_api_route(self, path: str, endpoint, **kwargs): ...
    def auth(self, credentials: HTTPBasicCredentials): ...
    def text2imgapi(self, txt2imgreq: models.StableDiffusionTxt2ImgProcessingAPI): ...
    def img2imgapi(self, img2imgreq: models.StableDiffusionImg2ImgProcessingAPI): ...
    def extras_single_image_api(self, req: models.ExtrasSingleImageRequest): ...
    def extras_batch_images_api(self, req: models.ExtrasBatchImagesRequest): ...
    def pnginfoapi(self, req: models.PNGInfoRequest): ...
    def progressapi(self, req: models.ProgressRequest): ...
    def interrogateapi(self, interrogatereq: models.InterrogateRequest): ...
    def get_config(self): ...
    def set_config(self, req: dict): ...
    def get_cmd_flags(self): ...
    def get_samplers(self): ...
    def get_sd_models(self): ...
    def get_memory(self): ...
    def get_extensions_list(self): ...

def script_name_to_index(name, scripts): ...
def validate_sampler_name(name): ...
def decode_base64_to_image(encoding): ...
def encode_pil_to_base64(image): ...
def api_middleware(app: FastAPI): ...
def verify_url(url): ...

Import

from modules.api.api import Api, decode_base64_to_image, encode_pil_to_base64

I/O Contract

Inputs

Name Type Required Description
app FastAPI Yes The FastAPI application instance to register routes on
queue_lock Lock Yes Thread lock for serializing generation requests
txt2imgreq StableDiffusionTxt2ImgProcessingAPI Yes (txt2img) Request model containing all txt2img generation parameters
img2imgreq StableDiffusionImg2ImgProcessingAPI Yes (img2img) Request model containing all img2img parameters including init images and mask
encoding str Yes (decode) Base64-encoded image string or HTTP URL to decode into a PIL Image

Outputs

Name Type Description
TextToImageResponse models.TextToImageResponse Contains base64 images list, generation parameters dict, and info JSON string
ImageToImageResponse models.ImageToImageResponse Contains base64 images list, generation parameters dict, and info JSON string
ProgressResponse models.ProgressResponse Contains progress float (0-1), ETA, state dict, optional current image, and info text
PNGInfoResponse models.PNGInfoResponse Contains parsed generation info string, metadata items dict, and parameters dict

Usage Examples

import requests
import base64

# Text-to-image generation
response = requests.post("http://localhost:7860/sdapi/v1/txt2img", json={
    "prompt": "a beautiful sunset over mountains",
    "negative_prompt": "blurry, low quality",
    "steps": 20,
    "sampler_name": "Euler a",
    "width": 512,
    "height": 512,
    "cfg_scale": 7,
    "seed": -1
})
result = response.json()
image_data = base64.b64decode(result["images"][0])

# Get current options
options = requests.get("http://localhost:7860/sdapi/v1/options").json()

# Change the model
requests.post("http://localhost:7860/sdapi/v1/options", json={
    "sd_model_checkpoint": "v1-5-pruned-emaonly.safetensors"
})

# Check progress
progress = requests.get("http://localhost:7860/sdapi/v1/progress").json()
print(f"Progress: {progress['progress'] * 100:.1f}%")

# Get available models
models = requests.get("http://localhost:7860/sdapi/v1/sd-models").json()

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment