How to use Stability AI API
Quick answer
Use the
stability_sdk Python package or direct REST API calls with your STABILITY_API_KEY to generate images from prompts. Install the SDK via pip install stability-sdk, then authenticate and call the generate method with your prompt and model parameters.PREREQUISITES
Python 3.8+Stability AI API key (set as STABILITY_API_KEY environment variable)pip install stability-sdk
Setup
Install the official stability-sdk Python package and set your API key as an environment variable.
- Install SDK:
pip install stability-sdk - Set environment variable:
export STABILITY_API_KEY='your_api_key'(Linux/macOS) orsetx STABILITY_API_KEY "your_api_key"(Windows)
pip install stability-sdk Step by step
Use the stability_sdk to generate an image from a text prompt with Stable Diffusion.
import os
from stability_sdk import client
# Initialize client with API key from environment
stability_api = client.StabilityInference(
key=os.environ["STABILITY_API_KEY"],
engine="stable-diffusion-v1-5", # Current recommended model
verbose=True
)
# Generate image from prompt
answers = stability_api.generate(
prompt="A futuristic cityscape at sunset, vibrant colors, detailed",
steps=30,
cfg_scale=7.0,
width=512,
height=512,
samples=1
)
# Save the generated image
for resp in answers:
for artifact in resp.artifacts:
if artifact.type == client.ARTIFACT_IMAGE:
with open("output.png", "wb") as f:
f.write(artifact.binary)
print("Image saved as output.png") output
Image saved as output.png
Common variations
You can customize the generation by changing the engine to other models like stable-diffusion-xl-beta-v2-2-2 for higher quality or use the REST API directly with requests. Async usage is not officially supported in the SDK but can be implemented with threading or asyncio wrappers.
import os
import requests
api_key = os.environ["STABILITY_API_KEY"]
url = "https://api.stability.ai/v1/generation/stable-diffusion-v1-5/text-to-image"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
payload = {
"text_prompts": [{"text": "A serene mountain lake at dawn"}],
"cfg_scale": 7,
"clip_guidance_preset": "FAST_BLUE",
"height": 512,
"width": 512,
"samples": 1,
"steps": 30
}
response = requests.post(url, headers=headers, json=payload)
if response.status_code == 200:
data = response.json()
# The image is base64 encoded
import base64
img_data = base64.b64decode(data["artifacts"][0]["base64"])
with open("output_rest.png", "wb") as f:
f.write(img_data)
print("Image saved as output_rest.png")
else:
print(f"Error: {response.status_code} - {response.text}") output
Image saved as output_rest.png
Troubleshooting
- If you get
401 Unauthorized, verify yourSTABILITY_API_KEYis correct and set in your environment. - For
429 Too Many Requests, you are hitting rate limits; reduce request frequency or contact Stability AI for quota increase. - If images fail to generate, check your prompt and parameters for validity and supported model names.
Key Takeaways
- Use the official
stability-sdkPython package for easiest integration with Stability AI API. - Set your API key securely in the
STABILITY_API_KEYenvironment variable before running code. - Customize generation with model engines, prompt, steps, and image size parameters.
- The REST API supports direct HTTP calls with JSON payloads and base64 image responses.
- Check error codes like 401 and 429 to troubleshoot authentication and rate limit issues.