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
pip install stability-sdk Env vars
STABILITY_API_KEY Imports
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
- Install the official stability-sdk Python package.
- Set your Stable Diffusion API key in the environment variable STABILITY_API_KEY.
- Import the client from stability_sdk and initialize it with your API key.
- Call the image generation method with your text prompt and desired parameters.
- Receive the generated image data and save or display it as needed.
Full code
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
{"engine": "stable-diffusion-v1-5", "prompt": "A futuristic cityscape at sunset", "steps": 30, "cfg_scale": 7.0, "width": 512, "height": 512, "samples": 1} Response
{"artifacts": [{"type": "image", "binary": "<image-bytes-base64>"}], "status": "success"} Extract
Save the binary data from response.artifacts[0].binary as a PNG fileVariants
Async version ›
Use when integrating Stable Diffusion image generation in asynchronous Python applications.
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.
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.
| Approach | Latency | Cost/call | Best for |
|---|---|---|---|
| Official SDK (synchronous) | ~5-10s | ~$0.02-$0.05 | Simple scripts and quick integration |
| Official SDK (async) | ~5-10s | ~$0.02-$0.05 | Async apps needing concurrency |
| HTTP REST API | ~5-10s | ~$0.02-$0.05 | Environments 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.