Complete tutorial on using Flux API for text-to-image generation. Learn advanced prompting techniques, parameter optimization, and integration best practices with code examples.
The Flux API represents the cutting edge of text-to-image generation technology. With its advanced diffusion models and intuitive interface, you can transform any text description into stunning, high-quality images. This comprehensive tutorial will guide you through everything you need to know to master the Flux API.
Flux API is a state-of-the-art text-to-image generation service that uses advanced diffusion models to create high-quality images from textual descriptions. Built on the latest AI research, it offers:
First, you'll need to authenticate your requests:
const FLUX_API_BASE = 'https://api.omnapi.com/v1/flux';
const API_KEY = process.env.OMNI_API_KEY;
const headers = {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json'
};
Here's your first image generation request:
async function generateImage(prompt) {
const response = await fetch(`${FLUX_API_BASE}/generate`, {
method: 'POST',
headers,
body: JSON.stringify({
prompt: prompt,
aspect_ratio: "1:1",
quality: "standard"
})
});
const result = await response.json();
return result;
}
// Example usage
const image = await generateImage("A serene mountain landscape at sunset");
console.log('Generated image:', image.imageUrl);
The API returns a structured response:
{
"success": true,
"imageUrl": "https://storage.omnapi.com/images/abc123.jpg",
"jobId": "job_abc123",
"metadata": {
"width": 1024,
"height": 1024,
"format": "JPEG",
"seed": 42,
"steps": 25,
"guidance_scale": 7.5
},
"creditsUsed": 10,
"processingTime": 3.2
}
Choose the perfect dimensions for your use case:
const aspectRatios = {
square: "1:1", // Social media posts, profile pictures
landscape: "16:9", // Banners, wallpapers
portrait: "9:16", // Mobile screens, stories
wide: "21:9", // Ultra-wide displays
photo: "4:3", // Standard photo format
cinema: "2.35:1" // Cinematic format
};
// Example with landscape format
const landscapeImage = await fetch(`${FLUX_API_BASE}/generate`, {
method: 'POST',
headers,
body: JSON.stringify({
prompt: "A futuristic city skyline with flying vehicles",
aspect_ratio: aspectRatios.landscape,
quality: "high"
})
});
Balance between speed and quality:
const qualitySettings = {
draft: {
quality: "draft", // Fastest, lower quality
steps: 15,
guidance_scale: 5.0
},
standard: {
quality: "standard", // Good balance
steps: 25,
guidance_scale: 7.5
},
high: {
quality: "high", // Best quality, slower
steps: 40,
guidance_scale: 10.0
}
};
// High-quality generation
const highQualityImage = await fetch(`${FLUX_API_BASE}/generate`, {
method: 'POST',
headers,
body: JSON.stringify({
prompt: "A detailed portrait of a wise old wizard",
...qualitySettings.high
})
});
Apply different artistic styles:
const styles = {
realistic: "photorealistic, detailed, high resolution",
artistic: "oil painting, artistic, brushstrokes",
anime: "anime style, manga, cel shading",
cartoon: "cartoon style, colorful, fun",
vintage: "vintage, retro, aged, film grain",
minimalist: "minimalist, clean, simple, modern",
cyberpunk: "cyberpunk, neon, futuristic, dark",
watercolor: "watercolor, soft, flowing, artistic"
};
async function generateStyledImage(basePrompt, style) {
const styledPrompt = `${basePrompt}, ${styles[style]}`;
return await fetch(`${FLUX_API_BASE}/generate`, {
method: 'POST',
headers,
body: JSON.stringify({
prompt: styledPrompt,
aspect_ratio: "1:1",
quality: "high"
})
});
}
// Generate anime-style image
const animeImage = await generateStyledImage(
"A magical forest with glowing flowers",
"anime"
);
Structure your prompts for best results:
function buildPrompt(subject, style, details, lighting, mood) {
const promptParts = [
subject, // Main subject
style, // Art style
details, // Additional details
lighting, // Lighting conditions
mood, // Overall mood
"high quality, detailed, 8k resolution" // Quality modifiers
].filter(Boolean);
return promptParts.join(", ");
}
// Example usage
const prompt = buildPrompt(
"A majestic eagle soaring", // subject
"realistic photography", // style
"mountain landscape background, clear sky", // details
"golden hour lighting", // lighting
"powerful and free" // mood
);
Exclude unwanted elements:
async function generateWithNegativePrompts(prompt, negativePrompt) {
return await fetch(`${FLUX_API_BASE}/generate`, {
method: 'POST',
headers,
body: JSON.stringify({
prompt: prompt,
negative_prompt: negativePrompt,
aspect_ratio: "16:9",
quality: "high"
})
});
}
const result = await generateWithNegativePrompts(
"A beautiful garden with flowers",
"people, cars, buildings, text, watermark, blurry, low quality"
);
const photographyPrompts = {
portrait: "Portrait of a confident businesswoman, professional headshot, studio lighting, shallow depth of field, Canon EOS R5, 85mm lens",
landscape: "Dramatic mountain landscape, golden hour, misty valleys, professional nature photography, wide angle lens, HDR",
macro: "Macro photography of a dewdrop on a rose petal, extreme close-up, vibrant colors, shallow focus, ring lighting",
street: "Street photography, bustling city market, candid moments, natural lighting, documentary style, 35mm film aesthetic"
};
const artisticPrompts = {
impressionist: "In the style of Claude Monet, impressionist painting, visible brushstrokes, light and color emphasis",
surreal: "Surrealist artwork, dreamlike, impossible architecture, Salvador Dali inspired, melting clocks, bizarre elements",
abstract: "Abstract expressionism, bold colors, geometric shapes, Jackson Pollock style, paint splatters",
minimalist: "Minimalist design, clean lines, negative space, monochromatic, Scandinavian style"
};
const conceptualPrompts = {
futuristic: "Futuristic concept art, sci-fi technology, holographic displays, neon lighting, cyberpunk aesthetic",
fantasy: "Fantasy art, magical creatures, enchanted forest, mystical atmosphere, D&D character design",
steampunk: "Steampunk invention, brass gears, steam pipes, Victorian era meets technology, industrial design",
postApocalyptic: "Post-apocalyptic wasteland, abandoned buildings, overgrown vegetation, dramatic sky, survival theme"
};
Generate multiple images efficiently:
class FluxBatchProcessor {
constructor(apiKey, maxConcurrent = 3) {
this.apiKey = apiKey;
this.maxConcurrent = maxConcurrent;
this.queue = [];
this.processing = 0;
}
async generateBatch(prompts) {
const results = [];
const promises = prompts.map(prompt => this.addToQueue(prompt));
return await Promise.all(promises);
}
async addToQueue(prompt) {
return new Promise((resolve, reject) => {
this.queue.push({ prompt, resolve, reject });
this.processQueue();
});
}
async processQueue() {
if (this.processing >= this.maxConcurrent || this.queue.length === 0) {
return;
}
this.processing++;
const { prompt, resolve, reject } = this.queue.shift();
try {
const result = await this.generateSingle(prompt);
resolve(result);
} catch (error) {
reject(error);
} finally {
this.processing--;
this.processQueue(); // Process next item
}
}
async generateSingle(prompt) {
const response = await fetch(`${FLUX_API_BASE}/generate`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt,
aspect_ratio: "1:1",
quality: "standard"
})
});
return await response.json();
}
}
// Usage example
const processor = new FluxBatchProcessor(API_KEY);
const prompts = [
"A red rose in a garden",
"A blue ocean with waves",
"A green forest with tall trees",
"A purple sunset over mountains"
];
const results = await processor.generateBatch(prompts);
console.log('Generated images:', results.map(r => r.imageUrl));
Implement intelligent caching:
const crypto = require('crypto');
const NodeCache = require('node-cache');
class FluxCache {
constructor(ttl = 3600) { // 1 hour default
this.cache = new NodeCache({ stdTTL: ttl });
}
generateCacheKey(prompt, params) {
const cacheString = JSON.stringify({ prompt, ...params });
return crypto.createHash('md5').update(cacheString).digest('hex');
}
async generateWithCache(prompt, params = {}) {
const cacheKey = this.generateCacheKey(prompt, params);
// Check cache first
const cached = this.cache.get(cacheKey);
if (cached) {
console.log('Cache hit for:', prompt.substring(0, 50));
return { ...cached, fromCache: true };
}
// Generate new image
console.log('Cache miss, generating:', prompt.substring(0, 50));
const result = await this.generateImage(prompt, params);
// Cache the result
this.cache.set(cacheKey, result);
return { ...result, fromCache: false };
}
async generateImage(prompt, params) {
const response = await fetch(`${FLUX_API_BASE}/generate`, {
method: 'POST',
headers,
body: JSON.stringify({
prompt,
...params
})
});
return await response.json();
}
}
// Usage
const fluxCache = new FluxCache();
const result = await fluxCache.generateWithCache(
"A beautiful sunset over the ocean",
{ aspect_ratio: "16:9", quality: "high" }
);
Generate product images for your store:
class ProductImageGenerator {
constructor(apiKey) {
this.apiKey = apiKey;
}
async generateProductImage(productDescription, style = "clean", background = "white") {
const prompt = this.buildProductPrompt(productDescription, style, background);
const response = await fetch(`${FLUX_API_BASE}/generate`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt,
aspect_ratio: "1:1",
quality: "high",
negative_prompt: "people, hands, text, watermark, low quality, blurry"
})
});
return await response.json();
}
buildProductPrompt(description, style, background) {
const styleModifiers = {
clean: "clean, minimalist, professional product photography",
lifestyle: "lifestyle photography, natural setting, warm lighting",
luxury: "luxury product shot, premium lighting, elegant composition",
vintage: "vintage style, retro aesthetic, film photography"
};
return `${description}, ${styleModifiers[style]}, ${background} background, high resolution, product photography, studio lighting, detailed, sharp focus`;
}
async generateVariations(productDescription, count = 4) {
const styles = ["clean", "lifestyle", "luxury", "vintage"];
const backgrounds = ["white", "gray", "natural", "dark"];
const variations = [];
for (let i = 0; i < count; i++) {
const style = styles[i % styles.length];
const background = backgrounds[i % backgrounds.length];
const image = await this.generateProductImage(productDescription, style, background);
variations.push({ image, style, background });
}
return variations;
}
}
// Usage example
const productGenerator = new ProductImageGenerator(API_KEY);
// Generate single product image
const sneakerImage = await productGenerator.generateProductImage(
"Modern white sneakers with blue accents",
"clean",
"white"
);
// Generate multiple variations
const variations = await productGenerator.generateVariations(
"Elegant gold wristwatch with leather strap",
4
);
Create engaging social media visuals:
class SocialMediaGenerator {
constructor(apiKey) {
this.apiKey = apiKey;
this.platforms = {
instagram: { ratio: "1:1", size: "1080x1080" },
instagram_story: { ratio: "9:16", size: "1080x1920" },
facebook_post: { ratio: "16:9", size: "1200x630" },
twitter_header: { ratio: "3:1", size: "1500x500" },
linkedin_post: { ratio: "1.91:1", size: "1200x628" }
};
}
async generateSocialPost(content, platform, style = "modern") {
const config = this.platforms[platform];
if (!config) {
throw new Error(`Unsupported platform: ${platform}`);
}
const prompt = this.buildSocialPrompt(content, style, platform);
const response = await fetch(`${FLUX_API_BASE}/generate`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt,
aspect_ratio: config.ratio,
quality: "high"
})
});
return await response.json();
}
buildSocialPrompt(content, style, platform) {
const styleModifiers = {
modern: "modern design, clean typography, minimal, trendy colors",
vibrant: "vibrant colors, energetic, bold design, eye-catching",
professional: "professional, corporate, clean, sophisticated",
creative: "creative design, artistic, unique layout, innovative",
vintage: "vintage aesthetic, retro colors, classic design"
};
const platformModifiers = {
instagram: "Instagram-style, visually appealing, hashtag ready",
instagram_story: "Instagram story format, mobile-first, engaging",
facebook_post: "Facebook post design, social media optimized",
twitter_header: "Twitter header style, brand focused",
linkedin_post: "LinkedIn professional, business-oriented"
};
return `${content}, ${styleModifiers[style]}, ${platformModifiers[platform]}, high quality design, social media graphics, no text overlay`;
}
async generateCampaign(theme, platforms = ["instagram", "facebook_post"]) {
const campaign = {};
for (const platform of platforms) {
campaign[platform] = await this.generateSocialPost(theme, platform);
}
return campaign;
}
}
// Usage
const socialGenerator = new SocialMediaGenerator(API_KEY);
// Generate single platform image
const instagramPost = await socialGenerator.generateSocialPost(
"Summer vacation tropical beach paradise",
"instagram",
"vibrant"
);
// Generate multi-platform campaign
const campaign = await socialGenerator.generateCampaign(
"New product launch celebration confetti",
["instagram", "facebook_post", "twitter_header"]
);
Generate images for blog posts:
class BlogIllustrationGenerator {
constructor(apiKey) {
this.apiKey = apiKey;
}
async generateBlogHero(title, topic, style = "modern") {
const prompt = this.buildBlogPrompt(title, topic, style, "hero");
return await this.generateImage(prompt, "21:9"); // Wide hero format
}
async generateBlogThumbnail(title, topic) {
const prompt = this.buildBlogPrompt(title, topic, "clean", "thumbnail");
return await this.generateImage(prompt, "16:9"); // Standard thumbnail
}
async generateInlineIllustration(concept, style = "illustrative") {
const prompt = `${concept}, ${style} illustration, clean background, concept art, high quality, detailed`;
return await this.generateImage(prompt, "4:3");
}
buildBlogPrompt(title, topic, style, type) {
const styleModifiers = {
modern: "modern, clean, professional, contemporary",
illustrative: "illustration, vector art, clean lines, informative",
photographic: "photographic, realistic, high quality, professional",
abstract: "abstract, conceptual, artistic, creative"
};
const typeModifiers = {
hero: "blog hero image, banner style, engaging, professional",
thumbnail: "thumbnail image, preview style, clear subject",
inline: "inline illustration, supporting content, clear concept"
};
return `${title} concept, ${topic} theme, ${styleModifiers[style]}, ${typeModifiers[type]}, no text, high resolution`;
}
async generateImage(prompt, aspectRatio) {
const response = await fetch(`${FLUX_API_BASE}/generate`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt,
aspect_ratio: aspectRatio,
quality: "high",
negative_prompt: "text, words, letters, watermark, low quality"
})
});
return await response.json();
}
}
// Usage example
const blogGenerator = new BlogIllustrationGenerator(API_KEY);
// Generate blog post images
const heroImage = await blogGenerator.generateBlogHero(
"The Future of AI in Healthcare",
"artificial intelligence medical technology",
"modern"
);
const thumbnailImage = await blogGenerator.generateBlogThumbnail(
"10 Tips for Better Photography",
"photography tips camera techniques"
);
const inlineIllustration = await blogGenerator.generateInlineIllustration(
"Data visualization dashboard with charts and graphs"
);
class FluxAPIError extends Error {
constructor(message, statusCode, details) {
super(message);
this.name = 'FluxAPIError';
this.statusCode = statusCode;
this.details = details;
}
}
class FluxAPIClient {
constructor(apiKey) {
this.apiKey = apiKey;
this.retryAttempts = 3;
this.retryDelay = 1000; // 1 second
}
async generateWithRetry(prompt, options = {}, attempt = 1) {
try {
return await this.generate(prompt, options);
} catch (error) {
if (attempt < this.retryAttempts && this.isRetryableError(error)) {
console.log(`Attempt ${attempt} failed, retrying in ${this.retryDelay}ms...`);
await this.delay(this.retryDelay * attempt); // Exponential backoff
return await this.generateWithRetry(prompt, options, attempt + 1);
}
throw error;
}
}
async generate(prompt, options = {}) {
const response = await fetch(`${FLUX_API_BASE}/generate`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt,
...options
})
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new FluxAPIError(
errorData.message || `HTTP ${response.status}: ${response.statusText}`,
response.status,
errorData
);
}
return await response.json();
}
isRetryableError(error) {
// Retry on server errors and rate limits
return error.statusCode >= 500 || error.statusCode === 429;
}
delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
// Usage with error handling
const client = new FluxAPIClient(API_KEY);
try {
const result = await client.generateWithRetry(
"A beautiful landscape with mountains and lakes",
{ aspect_ratio: "16:9", quality: "high" }
);
console.log('Success:', result.imageUrl);
} catch (error) {
if (error instanceof FluxAPIError) {
switch (error.statusCode) {
case 401:
console.error('Invalid API key');
break;
case 402:
console.error('Insufficient credits');
break;
case 429:
console.error('Rate limit exceeded');
break;
default:
console.error('API Error:', error.message);
}
} else {
console.error('Network Error:', error.message);
}
}
Track your API usage and performance:
class FluxMonitor {
constructor() {
this.stats = {
totalRequests: 0,
successfulRequests: 0,
failedRequests: 0,
totalCreditsUsed: 0,
averageResponseTime: 0,
responseTimeSum: 0
};
}
async monitoredGenerate(prompt, options = {}) {
const startTime = Date.now();
this.stats.totalRequests++;
try {
const result = await this.generate(prompt, options);
this.stats.successfulRequests++;
this.stats.totalCreditsUsed += result.creditsUsed || 0;
const responseTime = Date.now() - startTime;
this.stats.responseTimeSum += responseTime;
this.stats.averageResponseTime = this.stats.responseTimeSum / this.stats.successfulRequests;
console.log(`✅ Generated in ${responseTime}ms, Credits used: ${result.creditsUsed}`);
return result;
} catch (error) {
this.stats.failedRequests++;
console.error(`❌ Generation failed after ${Date.now() - startTime}ms:`, error.message);
throw error;
}
}
getStats() {
return {
...this.stats,
successRate: this.stats.totalRequests > 0
? (this.stats.successfulRequests / this.stats.totalRequests * 100).toFixed(2) + '%'
: '0%'
};
}
async generate(prompt, options) {
const response = await fetch(`${FLUX_API_BASE}/generate`, {
method: 'POST',
headers,
body: JSON.stringify({ prompt, ...options })
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
}
// Usage
const monitor = new FluxMonitor();
// Generate with monitoring
const result = await monitor.monitoredGenerate(
"A futuristic cityscape at night",
{ aspect_ratio: "16:9", quality: "high" }
);
// Check stats
console.log('Performance Stats:', monitor.getStats());
The Flux API opens up endless possibilities for creating stunning visual content programmatically. By mastering the techniques covered in this tutorial, you can:
Remember to start with simple prompts and gradually experiment with more complex techniques. The key to success with Flux API is understanding how to communicate your vision effectively through well-crafted prompts.
Ready to start creating amazing images? Get your Flux API key and begin your text-to-image journey today!
Comprehensive guide to integrating AI APIs into your applications. Learn about text-to-image, video generation, music creation, and more with practical examples and best practices.
Comprehensive comparison of leading AI APIs in 2025. Compare features, pricing, performance, and use cases for text-to-image, video generation, music creation, and more.
Discover innovative applications of Ace-step Music API for text-to-music generation. Explore real-world use cases, creative projects, and practical implementations for developers and creators.