Generate Images
Generate Images
Section titled “Generate Images”Generate AI images from text prompts using Cloudflare’s AI models.
Endpoint
Section titled “Endpoint”POST /api/generateRequest Body
Section titled “Request Body”| Parameter | Type | Required | Description |
|---|---|---|---|
prompt | string | Yes | Text description of the image to generate (min 3 characters) |
model | string | Yes | AI model ID to use for generation |
template_id | string | No | Optional template ID to use predefined settings |
metadata | object | No | Custom metadata to attach to the image |
Request Example
Section titled “Request Example”cURL:
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)Response
Section titled “Response”Success Response (200 OK)
Section titled “Success Response (200 OK)”{ "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}Response Fields
Section titled “Response Fields”| Field | Type | Description |
|---|---|---|
id | string | Unique image identifier (format: img_*) |
prompt | string | The text prompt used for generation |
model | string | AI model ID used |
r2_key | string | Internal R2 storage path |
r2_url | string | Public URL to access the image |
width | integer | Image width in pixels |
height | integer | Image height in pixels |
created_at | string | ISO 8601 timestamp |
user_id | string | User who generated the image |
cost | number | Generation cost in USD |
is_deleted | boolean | Soft delete flag |
Error Responses
Section titled “Error Responses”Invalid Prompt (400 Bad Request)
Section titled “Invalid Prompt (400 Bad Request)”{ "error": "Invalid prompt", "details": { "field": "prompt", "message": "Prompt must be at least 3 characters" }}Model Not Found (400 Bad Request)
Section titled “Model Not Found (400 Bad Request)”{ "error": "Invalid model", "details": { "model": "@cf/invalid/model", "message": "Model not found or not supported" }}IP Not Whitelisted (403 Forbidden)
Section titled “IP Not Whitelisted (403 Forbidden)”ForbiddenAI 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" }}Supported Models
Section titled “Supported Models”Use the /api/models endpoint to get the latest list of available models. Common models include:
| Model ID | Name | Speed | Quality | Cost |
|---|---|---|---|---|
@cf/black-forest-labs/flux-1-schnell | Flux 1 Schnell | Fast (2-3s) | High | $0.01 |
@cf/stabilityai/stable-diffusion-xl-base-1.0 | SDXL Base | Medium (5-7s) | Very High | $0.02 |
Prompt Engineering Tips
Section titled “Prompt Engineering Tips”Be Specific
Section titled “Be Specific”❌ Bad: “A house”
✅ Good: “A modern two-story house with large windows, surrounded by pine trees, during golden hour”
Include Style Descriptors
Section titled “Include Style Descriptors”- Photography styles: “photorealistic”, “macro photography”, “portrait”
- Art styles: “watercolor”, “oil painting”, “digital art”, “3D render”
- Moods: “dramatic”, “serene”, “vibrant”, “moody”
Use Technical Terms
Section titled “Use Technical Terms”- 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”
Example Prompts
Section titled “Example Prompts”Product Photography
A sleek wireless headphone on a marble surface, studio lighting,professional product photography, 8k, highly detailedLandscape
Mountain landscape at sunrise, misty valleys, pine forests,volumetric fog, golden hour lighting, photorealistic, 8kPortrait
Professional headshot of a business person, neutral gray background,soft lighting, sharp focus, photorealisticAbstract
Abstract geometric shapes in vibrant colors, 3D render,modern minimalist design, high contrastUsing Templates
Section titled “Using Templates”Save frequently used settings as templates:
// 1. Create a templateconst 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 templateconst 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 })});Batch Generation
Section titled “Batch Generation”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 }));}
// Usageconst prompts = [ 'Mountain landscape at sunset', 'Ocean waves during golden hour', 'Forest path in autumn'];
const results = await batchGenerate(prompts);console.log(results);Cost Calculation
Section titled “Cost Calculation”Image generation costs vary by model. View current pricing:
// Get model costsconst 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`);});Cost Analytics
Section titled “Cost Analytics”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}`);Performance
Section titled “Performance”Generation times vary by model and prompt complexity:
| Model | Typical Generation Time |
|---|---|
| Flux 1 Schnell | 2-3 seconds |
| Stable Diffusion XL | 5-7 seconds |
Webhook Notifications
Section titled “Webhook Notifications”For long-running batch jobs, use webhooks to get notified when complete:
// Note: Webhook support coming soonconst 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' })});Next Steps
Section titled “Next Steps”- List Images - Retrieve and filter generated images Learn more →
- Collections - Organize images into collections Collections →
- Models - Explore all available AI models View models →
- SDKs - Use official SDKs for easier integration Browse SDKs →