Article
image-generationstability-aistable-diffusion-3apipythonrest-apitext-to-imagegenerative-ai
Generate Images with the Stability AI Platform API
Use the Stability AI Platform to generate images from text prompts. This guide shows how to get your API key, make a REST API request to the Stable Diffusion 3 model, and save the resulting image using Python.
beginner15 min4 steps
The play
- Get Your API KeyFirst, you need an API key. Navigate to the Stability AI Platform dashboard at platform.stability.ai, create an account or log in, and go to the API Keys section to generate your key. For security, set it as an environment variable named 'STABILITY_API_KEY'.
- Set Up Your Python EnvironmentYou'll need Python installed. The only external library required is `requests` for making HTTP calls. It's a standard library for this purpose and you can install it using pip.
- Craft the API Request ScriptCreate a Python script to call the Stability AI Platform API. The script will send a POST request to the Stable Diffusion 3 endpoint. You'll specify your prompt, the model (e.g., 'sd3-medium'), and the desired output format in the request body.
- Save and View the Generated ImageAfter making the request, check if the status code is 200 (OK). If it is, the response body contains the image data. Write this binary data to a file (e.g., 'output.png') and then open it to see your generated image.
Starter code
import os
import requests
import sys
# --- Configuration ---
# Get API key from environment variable
API_KEY = os.getenv("STABILITY_API_KEY")
API_HOST = 'https://api.stability.ai'
OUTPUT_FILE = "output.png"
# --- Validation ---
if not API_KEY:
sys.exit("Error: STABILITY_API_KEY environment variable not set. Please get your key from https://platform.stability.ai/account/keys")
# --- API Request ---
print("Calling Stability AI Platform API...")
response = requests.post(
f"{API_HOST}/v2beta/stable-image/generate/sd3",
headers={
"authorization": f"Bearer {API_KEY}",
"accept": "image/*" # Request image binary in response
},
# Use 'files' for multipart/form-data, required by this endpoint
files={"none": ''},
# 'data' holds the parameters for generation
data={
"prompt": "A beautiful watercolor painting of a giant turtle swimming in a coral reef",
"model": "sd3-medium", # Specify the SD3 Medium model
"output_format": "png",
"aspect_ratio": "16:9"
},
)
# --- Response Handling ---
if response.status_code == 200:
try:
with open(OUTPUT_FILE, 'wb') as f:
f.write(response.content)
print(f"\nSuccess! Image saved to {os.path.abspath(OUTPUT_FILE)}")
except IOError as e:
sys.exit(f"Error: Could not write file to disk: {e}")
else:
print(f"\nError: API call failed with status code {response.status_code}")
try:
# Print the error details if the response is JSON
print(response.json())
except requests.exceptions.JSONDecodeError:
# Print the raw text if it's not JSON
print(response.text)
sys.exit(1)