# How to Use the AUTOMATIC1111 API: Complete Integration Guide for External Applications

> Integrate external apps with the AUTOMATIC1111 API. Learn to use its FastAPI REST interface for Stable Diffusion txt2img and img2img jobs. Start your integration today.

- Repository: [AUTOMATIC1111/stable-diffusion-webui](https://github.com/AUTOMATIC1111/stable-diffusion-webui)
- Tags: how-to-guide
- Published: 2026-02-24

---

**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`](https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/main/modules/api/api.py). When `create_api` is invoked from [`webui.py`](https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/main/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`](https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/main/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`](https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/main/modules/api/models.py), such as `StableDiffusionTxt2ImgProcessingAPI`. All generation calls acquire `self.queue_lock` (sourced from [`modules/call_queue.py`](https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/main/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:

```bash
python launch.py --api

```

To run the API without the Gradio interface (headless mode):

```bash
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:**

```bash
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:**

```python
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:

```bash
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:

```python
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.py`](https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/main/modules/api/models.py) for exact field names and types. The Pydantic models like `StableDiffusionTxt2ImgProcessingAPI` define 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 the `auth` dependency check.

- **Queue Awareness**: Remember that `self.queue_lock` serializes requests globally. Design clients to handle HTTP timeouts for long generations or implement progress polling via `/sdapi/v1/progress` for better user feedback.

- **Image Decoding**: Response models like `TextToImageResponse` return images as base64 strings in the `images` array. 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 `--api` or `--api-only` flags parsed by [`modules/shared_cmd_options.py`](https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/main/modules/shared_cmd_options.py).
- Core logic resides in [`modules/api/api.py`](https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/main/modules/api/api.py), with request schemas defined in [`modules/api/models.py`](https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/main/modules/api/models.py) and entry points in [`webui.py`](https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/main/webui.py).
- A global queue lock (`self.queue_lock` from [`modules/call_queue.py`](https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/main/modules/call_queue.py)) ensures sequential GPU processing to prevent memory errors.
- Authentication is optional via `--api-auth` and implemented as HTTP Basic Auth in the `auth` method.
- 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`](https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/main/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`](https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/main/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`](https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/main/modules/call_queue.py).

### Where are the request payload schemas defined?

Pydantic models for all endpoints are generated dynamically in [`modules/api/models.py`](https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/main/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.