Skip to content

Generate Images

Generate AI images from text prompts using Cloudflare’s AI models.

POST /api/generate
ParameterTypeRequiredDescription
promptstringYesText description of the image to generate (min 3 characters)
modelstringYesAI model ID to use for generation
template_idstringNoOptional template ID to use predefined settings
metadataobjectNoCustom metadata to attach to the image

cURL:

Terminal window
curl -X POST https://your-worker.workers.dev/api/generate \
-H "Content-Type: application/json" \
-d '{
"prompt": "A serene mountain landscape at sunset, photorealistic",
"model": "@cf/black-forest-labs/flux-1-schnell"
}'

JavaScript:

const response = await fetch('https://your-worker.workers.dev/api/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt: 'A serene mountain landscape at sunset, photorealistic',
model: '@cf/black-forest-labs/flux-1-schnell'
})
});
const image = await response.json();
console.log('Generated image:', image);

Python:

import requests
response = requests.post(
'https://your-worker.workers.dev/api/generate',
json={
'prompt': 'A serene mountain landscape at sunset, photorealistic',
'model': '@cf/black-forest-labs/flux-1-schnell'
}
)
image = response.json()
print('Generated image:', image)
{
"id": "img_1a2b3c4d5e6f",
"prompt": "A serene mountain landscape at sunset, photorealistic",
"model": "@cf/black-forest-labs/flux-1-schnell",
"r2_key": "generated/img_1a2b3c4d5e6f.png",
"r2_url": "https://your-bucket.r2.dev/generated/img_1a2b3c4d5e6f.png",
"width": 1024,
"height": 1024,
"created_at": "2024-01-15T10:30:00.000Z",
"user_id": "default_user",
"cost": 0.01,
"is_deleted": false
}
FieldTypeDescription
idstringUnique image identifier (format: img_*)
promptstringThe text prompt used for generation
modelstringAI model ID used
r2_keystringInternal R2 storage path
r2_urlstringPublic URL to access the image
widthintegerImage width in pixels
heightintegerImage height in pixels
created_atstringISO 8601 timestamp
user_idstringUser who generated the image
costnumberGeneration cost in USD
is_deletedbooleanSoft delete flag
{
"error": "Invalid prompt",
"details": {
"field": "prompt",
"message": "Prompt must be at least 3 characters"
}
}
{
"error": "Invalid model",
"details": {
"model": "@cf/invalid/model",
"message": "Model not found or not supported"
}
}
Forbidden

AI Generation Failed (500 Internal Server Error)

Section titled “AI Generation Failed (500 Internal Server Error)”
{
"error": "Image generation failed",
"details": {
"message": "AI service temporarily unavailable"
}
}

Use the /api/models endpoint to get the latest list of available models. Common models include:

Model IDNameSpeedQualityCost
@cf/black-forest-labs/flux-1-schnellFlux 1 SchnellFast (2-3s)High$0.01
@cf/stabilityai/stable-diffusion-xl-base-1.0SDXL BaseMedium (5-7s)Very High$0.02

❌ Bad: “A house”

✅ Good: “A modern two-story house with large windows, surrounded by pine trees, during golden hour”

  • Photography styles: “photorealistic”, “macro photography”, “portrait”
  • Art styles: “watercolor”, “oil painting”, “digital art”, “3D render”
  • Moods: “dramatic”, “serene”, “vibrant”, “moody”
  • Lighting: “golden hour”, “studio lighting”, “rim lighting”, “volumetric fog”
  • Camera: “wide angle”, “telephoto”, “bokeh”, “shallow depth of field”
  • Quality: “8k”, “highly detailed”, “sharp focus”, “intricate”

Product Photography

A sleek wireless headphone on a marble surface, studio lighting,
professional product photography, 8k, highly detailed

Landscape

Mountain landscape at sunrise, misty valleys, pine forests,
volumetric fog, golden hour lighting, photorealistic, 8k

Portrait

Professional headshot of a business person, neutral gray background,
soft lighting, sharp focus, photorealistic

Abstract

Abstract geometric shapes in vibrant colors, 3D render,
modern minimalist design, high contrast

Save frequently used settings as templates:

// 1. Create a template
const template = await fetch('https://your-worker.workers.dev/api/templates', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: 'Product Photography',
model: '@cf/black-forest-labs/flux-1-schnell',
default_prompt: 'Professional product photography, studio lighting, 8k'
})
});
// 2. Use the template
const image = await fetch('https://your-worker.workers.dev/api/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
prompt: 'Wireless headphones on marble surface',
template_id: template.id
})
});

Generate multiple images efficiently:

async function batchGenerate(prompts) {
const results = await Promise.allSettled(
prompts.map(prompt =>
fetch('https://your-worker.workers.dev/api/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
prompt,
model: '@cf/black-forest-labs/flux-1-schnell'
})
}).then(r => r.json())
)
);
return results.map((result, index) => ({
prompt: prompts[index],
success: result.status === 'fulfilled',
data: result.status === 'fulfilled' ? result.value : null,
error: result.status === 'rejected' ? result.reason : null
}));
}
// Usage
const prompts = [
'Mountain landscape at sunset',
'Ocean waves during golden hour',
'Forest path in autumn'
];
const results = await batchGenerate(prompts);
console.log(results);

Image generation costs vary by model. View current pricing:

// Get model costs
const models = await fetch('https://your-worker.workers.dev/api/models')
.then(r => r.json());
models.forEach(model => {
console.log(`${model.name}: $${model.cost_per_image} per image`);
});

Track your spending:

const analytics = await fetch('https://your-worker.workers.dev/api/analytics/costs')
.then(r => r.json());
console.log(`Total spent: $${analytics.total_cost}`);
console.log(`Images generated: ${analytics.total_images}`);
console.log(`Average cost per image: $${analytics.average_cost}`);

Generation times vary by model and prompt complexity:

ModelTypical Generation Time
Flux 1 Schnell2-3 seconds
Stable Diffusion XL5-7 seconds

For long-running batch jobs, use webhooks to get notified when complete:

// Note: Webhook support coming soon
const batch = await fetch('https://your-worker.workers.dev/api/batch/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
prompts: ['prompt1', 'prompt2', 'prompt3'],
model: '@cf/black-forest-labs/flux-1-schnell',
webhook_url: 'https://your-app.com/webhooks/generation-complete'
})
});