How to Use the AUTOMATIC1111 API: Complete Integration Guide for External Applications
The AUTOMATIC1111 API is a FastAPI-based REST interface that exposes Stable Diffusion generation endpoints under /sdapi/v1/, enabling external applications to submit txt2img and img2img jobs via HTTP requests when the server is started with --api.
The AUTOMATIC1111/stable-diffusion-webui repository ships with an embedded FastAPI server that transforms the Gradio interface into a programmatically accessible service. When launched with the --api flag, the application exposes REST endpoints for text-to-image generation, image manipulation, and system monitoring, making the AUTOMATIC1111 API ideal for automation pipelines and third-party integrations.
Architecture and Request Flow
The API implementation centers on the Api class defined in modules/api/api.py. When create_api is invoked from webui.py, it constructs a FastAPI application with custom middleware, authentication handlers, and endpoint registrations that process requests through a standardized pipeline.
FastAPI Server Initialization
The entry point api_only() in webui.py initializes the server without loading the Gradio UI. This function calls create_api, which returns a configured FastAPI instance ready to accept connections on the configured port (default 7860).
Middleware and Authentication Chain
Incoming requests pass through api_middleware, which records processing time in the X-Process-Time header and catches exceptions to convert them into JSON error responses. Optional HTTP Basic authentication is handled by the auth method when --api-auth=user:pass is supplied via command line.
Serialization and Queue Management
Request payloads are validated against Pydantic models dynamically generated in modules/api/models.py, such as StableDiffusionTxt2ImgProcessingAPI. All generation calls acquire self.queue_lock (sourced from modules/call_queue.py) to prevent GPU contention by ensuring only one job executes at a time.
Starting the API Server
You can launch the API in two modes depending on whether you need the web interface.
To run the full UI with API access enabled:
python launch.py --api
To run the API without the Gradio interface (headless mode):
python launch.py --api-only
Both modes invoke webui.api_only() to create the FastAPI app and start the server on the default port.
Core Endpoints and Implementation Examples
The REST API exposes endpoints under the /sdapi/v1/ prefix. Each endpoint follows a consistent pattern: parse the JSON payload, acquire the queue lock, invoke process_images from modules.processing, and return base64-encoded results wrapped in response models.
Text-to-Image Generation (/sdapi/v1/txt2img)
The txt2img endpoint accepts generation parameters matching the StableDiffusionProcessingTxt2Img schema defined in the models file.
cURL example:
curl -X POST http://127.0.0.1:7860/sdapi/v1/txt2img \
-H "Content-Type: application/json" \
-d '{
"prompt":"a cyberpunk city at night, ultra-realistic",
"steps":20,
"cfg_scale":7,
"width":512,
"height":512,
"sampler_index":"Euler a",
"send_images":true
}'
Python integration:
import requests
import base64
url = "http://127.0.0.1:7860/sdapi/v1/txt2img"
payload = {
"prompt": "a cyberpunk city at night, ultra-realistic",
"steps": 20,
"cfg_scale": 7,
"width": 512,
"height": 512,
"sampler_index": "Euler a",
"send_images": True
}
# Optional: Add auth if --api-auth was used
auth = ("username", "password")
response = requests.post(url, json=payload, auth=auth)
data = response.json()
# Decode and save first image from the images array
img_data = base64.b64decode(data["images"][0])
with open("output.png", "wb") as f:
f.write(img_data)
Image-to-Image Generation (/sdapi/v1/img2img)
For img2img operations, provide base64-encoded init images along with denoising strength parameters:
curl -X POST http://127.0.0.1:7860/sdapi/v1/img2img \
-H "Content-Type: application/json" \
-d '{
"init_images":["'$(base64 -w 0 input.png)'"],
"prompt":"stylize the portrait in oil painting",
"steps":30,
"denoising_strength":0.75,
"cfg_scale":8,
"send_images":true
}'
Monitoring Generation Progress (/sdapi/v1/progress)
Poll the progress endpoint to track job completion in real-time:
import requests
import time
progress_url = "http://127.0.0.1:7860/sdapi/v1/progress"
while True:
r = requests.get(progress_url)
p = r.json()
print(f"Progress: {p['progress']*100:.1f}% ETA: {p['eta_relative']:.1f}s")
if p["progress"] >= 1.0:
break
time.sleep(0.5)
Integration Best Practices
When building external applications that consume the AUTOMATIC1111 API, follow these implementation patterns:
-
Schema Validation: Reference
modules/api/models.pyfor exact field names and types. The Pydantic models likeStableDiffusionTxt2ImgProcessingAPIdefine all valid parameters including sampling steps, CFG scale, and seed values. -
Authentication Handling: If the server starts with
--api-auth, include HTTP Basic Auth headers in every request to satisfy theauthdependency check. -
Queue Awareness: Remember that
self.queue_lockserializes requests globally. Design clients to handle HTTP timeouts for long generations or implement progress polling via/sdapi/v1/progressfor better user feedback. -
Image Decoding: Response models like
TextToImageResponsereturn images as base64 strings in theimagesarray. Decode these from base64 before saving to disk or displaying in your application.
Summary
- The AUTOMATIC1111 API runs on FastAPI and exposes REST endpoints at
/sdapi/v1/when started with--apior--api-onlyflags parsed bymodules/shared_cmd_options.py. - Core logic resides in
modules/api/api.py, with request schemas defined inmodules/api/models.pyand entry points inwebui.py. - A global queue lock (
self.queue_lockfrommodules/call_queue.py) ensures sequential GPU processing to prevent memory errors. - Authentication is optional via
--api-authand implemented as HTTP Basic Auth in theauthmethod. - Responses include base64-encoded images, generation parameters, and infotext metadata wrapped in Pydantic response models.
Frequently Asked Questions
What port does the AUTOMATIC1111 API use by default?
The API server listens on port 7860 by default, matching the standard Gradio interface port. You can modify this with the --port argument when launching the application via launch.py.
How do I enable authentication for the API?
Start the server with the --api-auth username:password flag. The auth method in modules/api/api.py validates these credentials against the HTTP Basic Auth header on every request, returning a 401 response if authentication fails.
Can I run multiple generation jobs simultaneously through the API?
No. The implementation uses self.queue_lock to enforce sequential processing. This prevents GPU out-of-memory errors by ensuring only one process_images call runs at a time, as managed by the queue system in modules/call_queue.py.
Where are the request payload schemas defined?
Pydantic models for all endpoints are generated dynamically in modules/api/models.py. These include StableDiffusionTxt2ImgProcessingAPI for text generation and StableDiffusionImg2ImgProcessingAPI for image editing, which mirror the internal processing classes used by the Gradio UI.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →