← Back to Blog

Add AI Image Generation to Your Python App in 5 Minutes

February 2026 · 6 min read

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

Step 1: Get Your API Key (1 minute)

  1. Go to pixelapi.dev/app
  2. Sign in with Google
  3. 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?

SDXLFLUX Schnell
Cost3 credits ($0.003)3 credits ($0.003)
Speed8-13 seconds~25 seconds
Best forArtistic, stylized imagesPhotorealistic, text in images
Prompt styleKeyword-heavy works wellNatural 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

  1. Be specific in prompts — "a golden retriever playing in autumn leaves, soft natural lighting, shallow depth of field" beats "a dog"
  2. Include style keywords — "watercolor", "oil painting", "3D render", "photograph", "flat illustration"
  3. Mention composition — "centered", "wide shot", "close-up", "aerial view"
  4. Cache your results — Images are stored for 24h, but download them immediately for production use

Next Steps

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.