Code beginner · 3 min read

How to use Stable Diffusion API in Python

Direct answer
Use the official Stable Diffusion API by installing the SDK or sending HTTP requests with your API key, then call the image generation endpoint with a prompt in Python.

Setup

Install
bash
pip install stability-sdk
Env vars
STABILITY_API_KEY
Imports
python
from stability_sdk import client
import os
import base64

Examples

inA futuristic cityscape at sunset
outGenerated image URL or saved image file of a futuristic cityscape with warm sunset colors.
inA fantasy dragon flying over mountains
outGenerated image depicting a detailed dragon soaring above rugged mountains.
inAbstract colorful shapes
outGenerated abstract art with vibrant, colorful geometric shapes.

Integration steps

  1. Install the official stability-sdk Python package.
  2. Set your Stable Diffusion API key in the environment variable STABILITY_API_KEY.
  3. Import the client from stability_sdk and initialize it with your API key.
  4. Call the image generation method with your text prompt and desired parameters.
  5. Receive the generated image data and save or display it as needed.

Full code

python
from stability_sdk import client
import os

# Initialize the client with your API key from environment
stability_api = client.StabilityInference(
    key=os.environ["STABILITY_API_KEY"],
    engine="stable-diffusion-v1-5",  # or latest available engine
    verbose=True
)

# Define the prompt
prompt = "A futuristic cityscape at sunset"

# Generate image
answers = stability_api.generate(
    prompt=prompt,
    steps=30,
    cfg_scale=7.0,
    width=512,
    height=512,
    samples=1
)

# Save the first generated image
for resp in answers:
    for artifact in resp.artifacts:
        if artifact.type == client.ArtifactType.IMAGE:
            with open("output.png", "wb") as f:
                f.write(artifact.binary)
            print("Image saved as output.png")
output
Image saved as output.png

API trace

Request
json
{"engine": "stable-diffusion-v1-5", "prompt": "A futuristic cityscape at sunset", "steps": 30, "cfg_scale": 7.0, "width": 512, "height": 512, "samples": 1}
Response
json
{"artifacts": [{"type": "image", "binary": "<image-bytes-base64>"}], "status": "success"}
ExtractSave the binary data from response.artifacts[0].binary as a PNG file

Variants

Async version

Use when integrating Stable Diffusion image generation in asynchronous Python applications.

python
import asyncio
from stability_sdk import client
import os

async def generate_image():
    stability_api = client.StabilityInference(
        key=os.environ["STABILITY_API_KEY"],
        engine="stable-diffusion-v1-5",
        verbose=True
    )
    answers = await stability_api.generate_async(
        prompt="A fantasy dragon flying over mountains",
        steps=30,
        cfg_scale=7.0,
        width=512,
        height=512,
        samples=1
    )
    for resp in answers:
        for artifact in resp.artifacts:
            if artifact.type == client.ArtifactType.IMAGE:
                with open("dragon.png", "wb") as f:
                    f.write(artifact.binary)
                print("Image saved as dragon.png")

asyncio.run(generate_image())
HTTP REST API call

Use when you prefer direct HTTP calls without the SDK or in environments where SDK installation is not possible.

python
import os
import requests
import base64

api_key = os.environ["STABILITY_API_KEY"]
url = "https://api.stability.ai/v2beta/stable-image/generate/core"
headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json"
}
payload = {
    "engine": "stable-diffusion-v1-5",
    "prompt": "Abstract colorful shapes",
    "width": 512,
    "height": 512,
    "samples": 1,
    "steps": 30,
    "cfg_scale": 7.0
}
response = requests.post(url, headers=headers, json=payload)
response.raise_for_status()
image_data = response.json()["artifacts"][0]["base64"]
with open("abstract.png", "wb") as f:
    f.write(base64.b64decode(image_data))
print("Image saved as abstract.png")

Performance

Latency~5-10 seconds per 512x512 image generation depending on server load
Cost~$0.02 to $0.05 per image depending on resolution and provider pricing
Rate limitsTypically 20-30 requests per minute on standard API keys; check provider limits
  • Keep prompts concise to reduce processing time.
  • Use lower resolution (e.g., 512x512) for faster generation and lower cost.
  • Limit the number of samples per request to control usage.
ApproachLatencyCost/callBest for
Official SDK (synchronous)~5-10s~$0.02-$0.05Simple scripts and quick integration
Official SDK (async)~5-10s~$0.02-$0.05Async apps needing concurrency
HTTP REST API~5-10s~$0.02-$0.05Environments without SDK support

Quick tip

Use the official stability-sdk Python package for the simplest and most reliable Stable Diffusion API integration.

Common mistake

Forgetting to set the STABILITY_API_KEY environment variable or using an incorrect engine name causes authentication or request failures.

Verified 2026-04 · stable-diffusion-v1-5
Verify ↗