Add AI Image Generation to Your Python App in 5 Minutes
No ML experience needed. No GPU required. Just an API call.
This tutorial gets you from zero to generating AI images in your Python application using PixelAPI. By the end, you'll have working code you can drop into any project.
What You'll Need
- Python 3.7+
- The
requestslibrary (you probably already have it) - A PixelAPI account (free, takes 30 seconds)
Step 1: Get Your API Key (1 minute)
- Go to pixelapi.dev/app
- Sign in with Google
- Copy your API key from the dashboard
You get 100 free credits. SDXL costs 3 credits per image, FLUX costs 3. That's up to 100 free images to start.
Step 2: Generate Your First Image (2 minutes)
import requests
API_KEY = "your-api-key-here"
response = requests.post(
"https://api.pixelapi.dev/v1/generate",
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
},
json={
"prompt": "a cozy coffee shop interior, warm lighting, watercolor style",
"model": "sdxl"
}
)
data = response.json()
print(data["image_url"])
Run it. You'll get back a URL to your generated image. That's it — you just generated an AI image with 10 lines of code.
Step 3: Download the Image (1 minute)
The image URL is valid for 24 hours. For production use, download and store it yourself:
import requests
def generate_and_save(prompt, filename, model="sdxl"):
"""Generate an AI image and save it locally."""
response = requests.post(
"https://api.pixelapi.dev/v1/generate",
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
},
json={
"prompt": prompt,
"model": model
}
)
data = response.json()
# Download the image
img_response = requests.get(data["image_url"])
with open(filename, "wb") as f:
f.write(img_response.content)
print(f"Saved to {filename}")
return filename
# Generate some images
generate_and_save("sunset over mountains, oil painting", "sunset.png")
generate_and_save("minimalist logo, blue gradient", "logo.png", model="flux-schnell")
Step 4: Handle Errors Like a Pro (1 minute)
Production code needs error handling:
import requests
import time
def generate_image(prompt, model="sdxl", retries=3):
"""Generate an image with retry logic."""
for attempt in range(retries):
try:
response = requests.post(
"https://api.pixelapi.dev/v1/generate",
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
},
json={"prompt": prompt, "model": model},
timeout=60
)
if response.status_code == 200:
return response.json()["image_url"]
elif response.status_code == 429:
# Rate limited — wait and retry
time.sleep(2 ** attempt)
continue
else:
print(f"Error {response.status_code}: {response.text}")
return None
except requests.exceptions.Timeout:
print(f"Timeout on attempt {attempt + 1}")
continue
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
return None
print("All retries exhausted")
return None
# Usage
url = generate_image("a robot painting a landscape")
if url:
print(f"Generated: {url}")
Real-World Examples
Blog Thumbnail Generator
def generate_blog_thumbnail(title):
"""Generate a thumbnail image from a blog post title."""
prompt = f"blog header image for article titled '{title}', modern flat illustration, vibrant colors, 16:9 aspect ratio"
return generate_image(prompt, model="sdxl")
# Generate thumbnails for your posts
thumbnail = generate_blog_thumbnail("10 Python Tips You Didn't Know")
Avatar Generator
def generate_avatar(description, style="pixel art"):
"""Generate a user avatar."""
prompt = f"{description}, {style} style, centered, square composition, simple background"
return generate_image(prompt, model="flux-schnell")
avatar = generate_avatar("a friendly fox wearing glasses")
Batch Generation
import concurrent.futures
prompts = [
"a mountain landscape at sunrise",
"a cyberpunk cityscape at night",
"a peaceful zen garden",
"an underwater coral reef scene",
]
def gen(prompt):
return {"prompt": prompt, "url": generate_image(prompt)}
# Generate multiple images (be mindful of rate limits)
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
results = list(executor.map(gen, prompts))
for r in results:
print(f"{r['prompt']}: {r['url']}")
SDXL vs FLUX: Which Model to Use?
| SDXL | FLUX Schnell | |
|---|---|---|
| Cost | 3 credits ($0.003) | 3 credits ($0.003) |
| Speed | 8-13 seconds | ~25 seconds |
| Best for | Artistic, stylized images | Photorealistic, text in images |
| Prompt style | Keyword-heavy works well | Natural language works better |
Rule of thumb: Start with SDXL (cheaper and faster). Switch to FLUX when you need more photorealistic results or better text rendering.
Tips for Better Results
- Be specific in prompts — "a golden retriever playing in autumn leaves, soft natural lighting, shallow depth of field" beats "a dog"
- Include style keywords — "watercolor", "oil painting", "3D render", "photograph", "flat illustration"
- Mention composition — "centered", "wide shot", "close-up", "aerial view"
- Cache your results — Images are stored for 24h, but download them immediately for production use
Next Steps
- Read the full API docs for all available parameters
- Check your credit balance in the dashboard
- Try both models and see which works better for your use case
The free tier gives you 10 credits — enough to build and test a complete prototype before spending anything.
Built with PixelAPI — AI image generation at $0.003/image.