AI Image API: Python Tutorial
You can generate AI images from Python in under 10 lines of code. No GPU required, no complex model setup, no dependency headaches. Just send a POST request to an API endpoint and get an image URL back. This tutorial walks through every pattern you need: basic generation, error handling, async workflows, batch processing, and saving images to disk.
The code examples below use generic REST API patterns that apply to any AI image generation service (Stability AI, OpenAI DALL-E, Replicate, etc.). If you just want to generate images without writing code, try ZSky AI — a web-based AI video and image generator with unlimited free generation.
Prerequisites
You need Python 3.7+ and the requests library. If you do not have requests installed:
pip install requests
For async examples later in this tutorial, you will also need:
pip install aiohttp
Step 1: Your First Image Generation
Here is the simplest possible example. Most AI image APIs follow the same pattern: send a POST with your prompt and get an image URL back. Replace API_URL and API_KEY with your chosen provider's values.
import requests
API_KEY = "your_api_key_here"
API_URL = "https://api.example.com/v1/generate/image"
response = requests.post(
API_URL,
headers={"Authorization": f"Bearer {API_KEY}"},
json={
"prompt": "A mountain lake at sunrise, photorealistic",
"width": 1024,
"height": 1024
}
)
data = response.json()
print(data["image_url"]) # Direct download link
That is it.
Seven lines of meaningful code.The API handles all the heavy computation on GPU servers and returns a CDN-hosted image URL.You do not need to install any AI frameworks, download model weights, or configure CUDA drivers.Step 2: Save the Image to Disk
Most workflows need the image as a local file. Here is how to download and save it:
import requests API_KEY = "your_api_key_here" API_URL = "https://api.example.com/v1/generate/image" # Generate the image response = requests.post( API_URL, headers={"Authorization": f"Bearer {API_KEY}"}, json={ "prompt": "Cyberpunk street market at night, neon lights, rain", "width": 1024, "height": 768, "output_format": "png" } ) image_url = response.json()["image_url"] # Download and save image_data = requests.get(image_url) with open("generated_image.png", "wb") as f: f.write(image_data.content) print("Saved to generated_image.png")Step 5: Advanced Parameters
Most AI image APIs accept parameters like these to give you control over the output (check your provider's docs for exact names):
| Parameter | Type | Description |
|---|---|---|
prompt | string | Text description of the image to generate (required) |
negative_prompt | string | What to avoid in the output |
width | int | Image width: 512, 768, 1024, 2048 |
height | int | Image height: 512, 768, 1024, 2048 |
guidance_scale | float | Prompt adherence (1.0 to 20.0, default 7.5) |
seed | int | Reproducible results with same seed |
output_format | string | png, jpeg, or webp |
style | string | photorealistic, stylized, anime, illustration |
response = requests.post(
API_URL,
headers={"Authorization": f"Bearer {API_KEY}"},
json={
"prompt": "A cozy cabin in the woods, warm light from windows",
"negative_prompt": "blurry, low quality, distorted",
"width": 1024,
"height": 768,
"guidance_scale": 8.0,
"seed": 42,
"output_format": "webp",
"style": "photorealistic"
}
)
Using the same seed with the same prompt and parameters produces identical results, which is useful for reproducible workflows and A/B testing.
Step 6: Build a Flask Wrapper
Here is a minimal Flask app that wraps any AI image API into your own microservice:
from flask import Flask, request, jsonify
import requests as http
import os
app = Flask(__name__)
API_KEY = os.environ["IMAGE_API_KEY"]
API_URL = os.environ.get("IMAGE_API_URL", "https://api.example.com/v1/generate/image")
@app.route("/generate", methods=["POST"])
def generate():
prompt = request.json.get("prompt")
if not prompt:
return jsonify({"error": "prompt required"}), 400
resp = http.post(
API_URL,
headers={"Authorization": f"Bearer {API_KEY}"},
json={
"prompt": prompt,
"width": request.json.get("width", 1024),
"height": request.json.get("height", 1024)
},
timeout=60
)
if resp.status_code == 200:
return jsonify(resp.json())
return jsonify({"error": "generation failed"}), 500
if __name__ == "__main__":
app.run(port=8080)
This gives you a clean internal API that your frontend or other services can call without exposing external API authentication details.
Start Generating Images
Unlimited free generation. No credit card required. Create AI videos and images right in your browser.
Try ZSky Free →Common Patterns and Tips
Environment Variables for API Keys
Never hardcode API keys in source code. Use environment variables:
import os
API_KEY = os.environ["IMAGE_API_KEY"]
# Set in terminal: export IMAGE_API_KEY=your_key_here
Polling for Async Jobs
For high-resolution images or video, the API returns a job ID. Poll the status endpoint until it completes:
import time
# Submit the job
resp = requests.post(
API_URL,
headers={"Authorization": f"Bearer {API_KEY}"},
json={"prompt": "Epic landscape", "width": 2048, "height": 2048}
)
job_id = resp.json()["job_id"]
# Poll until done
while True:
status = requests.get(
f"https://api.example.com/v1/status/{job_id}",
headers={"Authorization": f"Bearer {API_KEY}"}
).json()
if status["status"] == "completed":
print(f"Done: {status['result_url']}")
break
elif status["status"] == "failed":
print(f"Failed: {status['error']}")
break
time.sleep(2) # Check every 2 seconds
Rate Limit Awareness
Every API response includes rate limit headers. Use them to avoid hitting limits:
remaining = int(response.headers.get("X-RateLimit-Remaining", 0))
reset_time = int(response.headers.get("X-RateLimit-Reset", 0))
if remaining < 5:
print(f"Only {remaining} requests left. Resets at {reset_time}")
Frequently Asked Questions
What Python libraries do I need to call an AI image API?
You only need the requests library, which comes pre-installed with most Python distributions. For async workflows, use aiohttp or httpx. No special SDK is required — most AI image APIs use standard REST endpoints that any HTTP client can call.
Does ZSky AI have a public API?
ZSky AI does not offer a self-serve public API. API access is available for enterprise customers only — contact [email protected] for details. Individual users can generate videos and images through the web platform at zsky.ai/create with unlimited free generation. Paid plans start at $19/mo (Starter) and $19/mo (Pro).
How do I handle errors when calling an AI image API from Python?
Check the HTTP status code of the response. 200 means success. 400 means bad request parameters. 429 means rate limited, so implement exponential backoff. 500 means server error, so retry after a short delay. Always wrap API calls in try-except blocks to handle network errors.
Can I generate multiple AI images in a single Python script?
Yes. Many AI image APIs support batch endpoints, or you can use asyncio with aiohttp to send concurrent requests. Both approaches are significantly faster than sequential single-image calls.
How long does it take to generate an AI image via API?
Typical AI image generation takes 3 to 20 seconds depending on resolution and model complexity. Most APIs return a job ID immediately that you can poll for the result or use a webhook callback.
Generate AI Videos and Images
Unlimited free generation. 1080p videos with audio. Pro from $19/mo. Enterprise API access available — contact [email protected].
Try ZSky Free →