Example: Text-to-Image Generation
Complete example of generating images from text using Atlas Cloud API
Overview
This tutorial walks through a complete text-to-image generation workflow using the Atlas Cloud API — from submitting the request to retrieving the final image.
Prerequisites
- An Atlas Cloud account with API key
- Python 3.7+ with
requestslibrary, or Node.js 18+
Complete Python Example
import requests
import time
import os
API_KEY = os.environ.get("ATLASCLOUD_API_KEY", "your-api-key")
BASE_URL = "https://api.atlascloud.ai/api/v1"
def generate_image(prompt, model="seedream-3.0"):
"""Submit an image generation task."""
response = requests.post(
f"{BASE_URL}/model/generateImage",
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
},
json={
"model": model,
"prompt": prompt
}
)
response.raise_for_status()
return response.json().get("predictionId")
def wait_for_result(prediction_id, interval=2, timeout=120):
"""Poll for generation result."""
elapsed = 0
while elapsed < timeout:
response = requests.get(
f"{BASE_URL}/model/getResult?predictionId={prediction_id}",
headers={"Authorization": f"Bearer {API_KEY}"}
)
result = response.json()
status = result.get("status")
if status == "completed":
return result.get("output")
elif status == "failed":
raise Exception(f"Failed: {result.get('error')}")
print(f" Status: {status} ({elapsed}s)")
time.sleep(interval)
elapsed += interval
raise TimeoutError("Generation timed out")
# Generate an image
prompt = "A majestic snow-capped mountain reflected in a crystal-clear lake at sunrise, photorealistic"
print(f"Generating image: {prompt}")
prediction_id = generate_image(prompt)
print(f"Task submitted: {prediction_id}")
image_url = wait_for_result(prediction_id)
print(f"Image ready: {image_url}")Complete Node.js Example
const API_KEY = process.env.ATLASCLOUD_API_KEY || "your-api-key";
const BASE_URL = "https://api.atlascloud.ai/api/v1";
async function generateImage(prompt, model = "seedream-3.0") {
const response = await fetch(`${BASE_URL}/model/generateImage`, {
method: "POST",
headers: {
Authorization: `Bearer ${API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ model, prompt }),
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
return data.predictionId;
}
async function waitForResult(predictionId, interval = 2000, timeout = 120000) {
const start = Date.now();
while (Date.now() - start < timeout) {
const response = await fetch(
`${BASE_URL}/model/getResult?predictionId=${predictionId}`,
{ headers: { Authorization: `Bearer ${API_KEY}` } }
);
const result = await response.json();
if (result.status === "completed") return result.output;
if (result.status === "failed") throw new Error(result.error);
console.log(` Status: ${result.status}`);
await new Promise((r) => setTimeout(r, interval));
}
throw new Error("Timeout");
}
// Run
const prompt =
"A majestic snow-capped mountain reflected in a crystal-clear lake at sunrise, photorealistic";
console.log(`Generating: ${prompt}`);
const predictionId = await generateImage(prompt);
console.log(`Task: ${predictionId}`);
const imageUrl = await waitForResult(predictionId);
console.log(`Image: ${imageUrl}`);cURL Example
# Step 1: Submit generation task
PREDICTION_ID=$(curl -s -X POST https://api.atlascloud.ai/api/v1/model/generateImage \
-H "Authorization: Bearer $ATLASCLOUD_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "seedream-3.0",
"prompt": "A majestic snow-capped mountain reflected in a crystal-clear lake"
}' | jq -r '.predictionId')
echo "Prediction ID: $PREDICTION_ID"
# Step 2: Poll for result
while true; do
RESULT=$(curl -s "https://api.atlascloud.ai/api/v1/model/getResult?predictionId=$PREDICTION_ID" \
-H "Authorization: Bearer $ATLASCLOUD_API_KEY")
STATUS=$(echo $RESULT | jq -r '.status')
echo "Status: $STATUS"
if [ "$STATUS" = "completed" ]; then
echo $RESULT | jq -r '.output'
break
elif [ "$STATUS" = "failed" ]; then
echo "Failed: $(echo $RESULT | jq -r '.error')"
break
fi
sleep 2
doneTips
- Model selection: Try different models for different styles. Seedream excels at photorealistic images, FLUX is great for artistic styles
- Prompt engineering: Be specific about style, composition, lighting, colors, and mood
- Batch generation: Submit multiple requests in parallel for batch image generation
- Error handling: Always check for
failedstatus and handle timeouts gracefully
Next Steps
- Image-to-Video Example — Animate generated images into videos
- Image Generation Models — Explore all available image models
- LoRA Guide — Use custom LoRA models for style control
- API Reference — Full API specification