Factory.ai

Open-Source Wikis

/

Stable Diffusion WebUI

/

API

AUTOMATIC1111/stable-diffusion-webui

API

Active contributors: AUTOMATIC1111, Aarni Koskela, w-e-w, missionfloyd

Purpose

A FastAPI service that exposes ~50 routes for driving the webui programmatically. Most routes mirror UI features 1:1 — same params, same processing pipeline, same model. The API can run alongside the Gradio UI (with --api) or as a headless server (with --nowebui).

Where the code lives

Concern File
Route registration Api.__init__ in modules/api/api.py
Pydantic models modules/api/models.py
Auto-generated Txt2Img/Img2Img request models helpers in modules/api/models.py introspect StableDiffusionProcessing to build the Pydantic class
Bootstrap webui.py:create_api() constructs the Api, attaching it to shared.demo's FastAPI app or to a fresh one for --nowebui mode
Auth --api-auth user:pass[,user:pass] and --api-auth-file consumed by Api.app.dependency_overrides

Auth and CORS

  • --api-auth enables HTTPBasic on every /sdapi/v1/* route. Multiple credentials can be supplied comma-separated.
  • The --gradio-auth flag covers the UI; both can be used together.
  • CORS is explicitly stripped from Gradio's permissive default (see webui.py) — extensions or front-ends running on a different origin must use --cors-allow-origins or --cors-allow-origins-regex.
  • Server-side resource access (/sdapi/v1/extra-single-image with a URL) is gated behind api_enable_requests/api_forbid_local_requests settings to prevent SSRF (see security.md).

Routes by category

A non-exhaustive map of the surface, derived from Api.__init__:

Generation

Method + path Pydantic Notes
POST /sdapi/v1/txt2img StableDiffusionTxt2ImgProcessingAPI → TextToImageResponse Calls process_images()
POST /sdapi/v1/img2img StableDiffusionImg2ImgProcessingAPI → ImageToImageResponse
POST /sdapi/v1/extra-single-image ExtrasSingleImageRequest → ExtrasSingleImageResponse Extras tab path
POST /sdapi/v1/extra-batch-images ExtrasBatchImagesRequest → ExtrasBatchImagesResponse Same logic, batch input
POST /sdapi/v1/png-info Reads PNG metadata into infotext
POST /sdapi/v1/interrogate CLIP / deepdanbooru caption an image

Process control

Method + path Notes
GET /sdapi/v1/progress Live progress + preview latents; polled by the UI's progressbar.js
POST /sdapi/v1/interrupt Abort the current generation cleanly
POST /sdapi/v1/skip Skip the current image, continue the batch
POST /sdapi/v1/server-stop Only registered when --api-server-stop is passed (used by tests)
POST /sdapi/v1/server-restart Same gating
POST /sdapi/v1/server-kill Same gating

Configuration

Method + path Notes
GET /sdapi/v1/options Read shared.opts
POST /sdapi/v1/options Write a subset of options
GET /sdapi/v1/cmd-flags Read parsed cmd_opts
GET /sdapi/v1/samplers List (name, aliases, options)
GET /sdapi/v1/schedulers List schedulers
GET /sdapi/v1/upscalers List upscalers
GET /sdapi/v1/latent-upscale-modes List latent-upscale variants
GET /sdapi/v1/sd-models List checkpoints
GET /sdapi/v1/sd-vae List VAEs
GET /sdapi/v1/hypernetworks
GET /sdapi/v1/face-restorers
GET /sdapi/v1/realesrgan-models
GET /sdapi/v1/prompt-styles
GET /sdapi/v1/embeddings
POST /sdapi/v1/refresh-embeddings Rescan disk
POST /sdapi/v1/refresh-checkpoints
POST /sdapi/v1/refresh-vae
POST /sdapi/v1/unload-checkpoint Free GPU memory
POST /sdapi/v1/reload-checkpoint
GET /sdapi/v1/memory Current GPU/CPU memory

Training and creation

Method + path Notes
POST /sdapi/v1/create/embedding Create a new (untrained) embedding
POST /sdapi/v1/create/hypernetwork
POST /sdapi/v1/train/embedding Run textual-inversion training
POST /sdapi/v1/train/hypernetwork Run hypernet training

Scripts and extensions

Method + path Notes
GET /sdapi/v1/scripts List available scripts
GET /sdapi/v1/script-info Schema for each script's args (used by external clients to build forms)
GET /sdapi/v1/extensions List installed extensions

Per-extension routes

Extensions can register their own FastAPI routes from on_app_started(callback) — for example, the Lora browser uses /sd_extra_networks/* paths. These are not in the standard table; consult the extension's source.

Pydantic models

models.py declares response shapes by hand and request shapes mostly by introspecting the StableDiffusionProcessing* dataclasses. The introspection helpers (PydanticModelGenerator) build a Pydantic class from the field annotations:

class StableDiffusionTxt2ImgProcessingAPI(
    PydanticModelGenerator(
        "StableDiffusionProcessingTxt2Img",
        StableDiffusionProcessingTxt2Img,
        [
            {"key": "sampler_index", "type": str, "default": "Euler"},
            ...
        ]
    ).generate_model()
): pass

This means most StableDiffusionProcessing fields are automatically part of the API request body. Adding a new field to the dataclass usually exposes it without further work.

Script args

Both txt2img and img2img requests accept:

  • script_name — the title of a one-shot script to run (mutually exclusive with normal generation).
  • script_args — positional args for that script.
  • alwayson_scripts: dict[str, dict[str, list]] — e.g. {"controlnet": {"args": [...]}}. Each key is matched against Script.title() and the args are spliced into the right position.

get_scripts_list() and get_script_info() return enough information for a client to build the right script_args payload by name.

Returned shape

A txt2img response looks like:

{
    "images": ["<base64>"],
    "parameters": {...},  // the request echo
    "info": "<infotext string>"
}

info is the standard infotext format that the UI's "Read generation parameters" can ingest. parameters is the request body, useful for replay.

API-only mode

python launch.py --nowebui --api (or just --nowebui) skips Gradio entirely. webui.py:api_only() is the entry point: it builds a fresh FastAPI app, attaches Api, and runs uvicorn directly. Default port is 7861 (vs 7860 for the UI).

OpenAPI and Redoc docs are at /docs and /redoc respectively, with the route metadata coming from FastAPI auto-generation.

Integration points

  • script_callbacks.on_app_started(callback) lets extensions register their own routes on the same app object.
  • The same queue_lock from modules/call_queue.py is used by API handlers, so concurrent UI + API requests serialise on the GPU.
  • infotext_utils is shared by API and UI for round-trip parsing.

Entry points for modification

  • Adding a route — add a method to Api and a corresponding self.add_api_route(...) line in __init__. If the new route returns model data, declare a Pydantic model in models.py.
  • Adding a parameter to txt2img/img2img — add the field to StableDiffusionProcessingTxt2Img / Img2Img. The Pydantic class refreshes from introspection.
  • Adding auth/rate-limiting — wrap the relevant routes with FastAPI dependencies. There's no built-in rate limiter; users put a reverse proxy in front for that.

Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.

API – Stable Diffusion WebUI wiki | Factory