Welcome to the Flux Kontext API!
This quickstart guide will walk you through the essential steps to start generating and editing images using state-of-the-art AI models.
Overview
Generated images are stored for 14 days and automatically expire after that period.
Authentication
All API requests require authentication via Bearer Token.
Add to Request Headers
Include your API key in all requests: Authorization: Bearer YOUR_API_KEY
Keep your API key secure and never share it publicly. If compromised, reset it immediately in the management page.
Basic Usage
1. Generate an Image from Text
Start by creating your first text-to-image generation task:
curl -X POST "https://api.kie.ai/api/v1/flux/kontext/generate" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "A serene mountain landscape at sunset with a lake reflecting the orange sky",
"aspectRatio": "16:9",
"model": "flux-kontext-pro"
}'
Response:
{
"code" : 200 ,
"msg" : "success" ,
"data" : {
"taskId" : "task_flux_abc123"
}
}
2. Edit an Existing Image
Modify an existing image using text prompts:
curl -X POST "https://api.kie.ai/api/v1/flux/kontext/generate" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Add colorful hot air balloons floating in the sky",
"inputImage": "https://example.com/landscape.jpg",
"aspectRatio": "16:9"
}'
3. Check Generation Status
Use the returned taskId to monitor progress:
curl -X GET "https://api.kie.ai/api/v1/flux/kontext/record-info?taskId=task_flux_abc123" \
-H "Authorization: Bearer YOUR_API_KEY"
Status Values:
0: GENERATING - Task is currently being processed
1: SUCCESS - Task completed successfully
2: CREATE_TASK_FAILED - Failed to create the task
3: GENERATE_FAILED - Task creation succeeded but generation failed
Complete Workflow Example
Here’s a complete example that generates an image and waits for completion:
class FluxKontextAPI {
constructor ( apiKey ) {
this . apiKey = apiKey ;
this . baseUrl = 'https://api.kie.ai/api/v1/flux/kontext' ;
}
async generateImage ( prompt , options = {}) {
const response = await fetch ( ` ${ this . baseUrl } /generate` , {
method: 'POST' ,
headers: {
'Authorization' : `Bearer ${ this . apiKey } ` ,
'Content-Type' : 'application/json'
},
body: JSON . stringify ({
prompt ,
aspectRatio: options . aspectRatio || '16:9' ,
model: options . model || 'flux-kontext-pro' ,
enableTranslation: options . enableTranslation !== false ,
outputFormat: options . outputFormat || 'jpeg' ,
... options
})
});
const result = await response . json ();
if ( ! response . ok || result . code !== 200 ) {
throw new Error ( `Generation failed: ${ result . msg || 'Unknown error' } ` );
}
return result . data . taskId ;
}
async editImage ( prompt , inputImage , options = {}) {
return this . generateImage ( prompt , {
... options ,
inputImage
});
}
async waitForCompletion ( taskId , maxWaitTime = 300000 ) { // 5 minutes max
const startTime = Date . now ();
while ( Date . now () - startTime < maxWaitTime ) {
const status = await this . getTaskStatus ( taskId );
switch ( status . successFlag ) {
case 0 :
console . log ( 'Task is generating, continue waiting...' );
break ;
case 1 :
console . log ( 'Generation completed successfully!' );
return status . response ;
case 2 :
const createError = status . errorMessage || 'Create task failed' ;
console . error ( 'Create task failed:' , createError );
if ( status . errorCode ) {
console . error ( 'Error code:' , status . errorCode );
}
throw new Error ( createError );
case 3 :
const generateError = status . errorMessage || 'Generation failed' ;
console . error ( 'Generation failed:' , generateError );
if ( status . errorCode ) {
console . error ( 'Error code:' , status . errorCode );
}
throw new Error ( generateError );
default :
console . log ( `Unknown status: ${ status . successFlag } ` );
if ( status . errorMessage ) {
console . error ( 'Error message:' , status . errorMessage );
}
break ;
}
// Wait 3 seconds before next check
await new Promise ( resolve => setTimeout ( resolve , 3000 ));
}
throw new Error ( 'Generation timeout' );
}
async getTaskStatus ( taskId ) {
const response = await fetch ( ` ${ this . baseUrl } /record-info?taskId= ${ taskId } ` , {
method: 'GET' ,
headers: {
'Authorization' : `Bearer ${ this . apiKey } `
}
});
const result = await response . json ();
if ( ! response . ok || result . code !== 200 ) {
throw new Error ( `Status check failed: ${ result . msg || 'Unknown error' } ` );
}
return result . data ;
}
}
// Usage Example
async function main () {
const api = new FluxKontextAPI ( 'YOUR_API_KEY' );
try {
// Text-to-Image Generation
console . log ( 'Starting image generation...' );
const taskId = await api . generateImage (
'A futuristic cityscape at night with neon lights and flying cars' ,
{
aspectRatio: '16:9' ,
model: 'flux-kontext-max' ,
promptUpsampling: true
}
);
// Wait for completion
console . log ( `Task ID: ${ taskId } . Waiting for completion...` );
const result = await api . waitForCompletion ( taskId );
console . log ( 'Image generated successfully!' );
console . log ( 'Result Image URL:' , result . resultImageUrl );
console . log ( 'Original Image URL (valid 10 min):' , result . originImageUrl );
// Image Editing Example
console . log ( ' \n Starting image editing...' );
const editTaskId = await api . editImage (
'Add rainbow in the sky' ,
result . resultImageUrl ,
{ aspectRatio: '16:9' }
);
const editResult = await api . waitForCompletion ( editTaskId );
console . log ( 'Image edited successfully!' );
console . log ( 'Edited Image URL:' , editResult . resultImageUrl );
} catch ( error ) {
console . error ( 'Error:' , error . message );
}
}
main ();
Advanced Features
Model Selection
Choose the appropriate model based on your needs:
// Standard model for balanced performance
const taskId = await api . generateImage ( 'Beautiful landscape' , {
model: 'flux-kontext-pro'
});
// Enhanced model for complex scenes and higher quality
const taskId = await api . generateImage ( 'Complex architectural interior with intricate details' , {
model: 'flux-kontext-max'
});
Aspect Ratio Options
Support for various image formats:
const aspectRatios = {
'ultra-wide' : '21:9' , // Cinematic displays
'widescreen' : '16:9' , // HD video, desktop wallpapers
'standard' : '4:3' , // Traditional displays
'square' : '1:1' , // Social media posts
'portrait' : '3:4' , // Magazine layouts
'mobile' : '9:16' , // Smartphone wallpapers
'ultra-tall' : '16:21' // Mobile app splash screens
};
const taskId = await api . generateImage ( 'Modern office space' , {
aspectRatio: aspectRatios . widescreen
});
Prompt Enhancement
Let the AI optimize your prompts:
const taskId = await api . generateImage ( 'sunset' , {
promptUpsampling: true // AI will enhance the prompt for better results
});
Safety Tolerance Control
Adjust content moderation levels:
// For image generation (0-6)
const taskId = await api . generateImage ( 'Artistic concept' , {
safetyTolerance: 4 // More permissive for artistic content
});
// For image editing (0-2)
const editTaskId = await api . editImage ( 'Stylistic changes' , inputImage , {
safetyTolerance: 2 // Balanced moderation
});
Using Callbacks
Set up webhook callbacks for automatic notifications:
const taskId = await api . generateImage ( 'Digital art masterpiece' , {
aspectRatio: '1:1' ,
callBackUrl: 'https://your-server.com/flux-callback'
});
// Your callback endpoint will receive:
app . post ( '/flux-callback' , ( req , res ) => {
const { code , data } = req . body ;
if ( code === 200 ) {
console . log ( 'Images ready:' , data . info . resultImageUrl );
} else {
console . log ( 'Generation failed:' , req . body . msg );
}
res . status ( 200 ). json ({ status: 'received' });
});
Learn More About Callbacks Set up webhook callbacks to receive automatic notifications when your images are ready.
Error Handling
Common error scenarios and how to handle them:
Content Policy Violations (Code 400)
try {
const taskId = await api . generateImage ( 'inappropriate content' );
} catch ( error ) {
if ( error . data . code === 400 ) {
console . log ( 'Please modify your prompt to comply with content policies' );
}
}
Safety Tolerance Out of Range (Code 500)
try {
const taskId = await api . generateImage ( 'artwork' , {
safetyTolerance: 7 // Invalid for generation mode (max 6)
});
} catch ( error ) {
console . log ( 'Safety tolerance should be 0-6 for generation, 0-2 for editing' );
}
const delay = ( ms ) => new Promise ( resolve => setTimeout ( resolve , ms ));
async function generateWithRetry ( prompt , options , maxRetries = 3 ) {
for ( let i = 0 ; i < maxRetries ; i ++ ) {
try {
return await api . generateImage ( prompt , options );
} catch ( error ) {
if ( error . data . code === 429 && i < maxRetries - 1 ) {
await delay ( Math . pow ( 2 , i ) * 1000 ); // Exponential backoff
continue ;
}
throw error ;
}
}
}
Best Practices
Use Callbacks : Set up webhook callbacks instead of polling for better performance
Model Selection : Use flux-kontext-pro for standard tasks, flux-kontext-max for complex scenes
Prompt Engineering : Use detailed, specific prompts for better results
Image Preprocessing : Ensure input images are accessible and optimized
Download Management : Download images promptly as they expire after 14 days
Translation Settings : Set enableTranslation: false if your prompts are already in English
Important Limitations
Language Support : Prompts only support English (use enableTranslation: true for auto-translation)
Image Storage : Generated images expire after 14 days
Original Image URLs : Valid for only 10 minutes after generation
Safety Tolerance : Generation mode (0-6), Editing mode (0-2)
Input Images : Must be publicly accessible URLs
Supported Parameters
Core Parameters
Parameter Type Description Default promptstring Required . Text description for generation/editing- aspectRatiostring Output image aspect ratio 16:9modelstring flux-kontext-pro or flux-kontext-maxflux-kontext-prooutputFormatstring jpeg or pngjpeg
Optional Parameters
Parameter Type Description Default inputImagestring URL for image editing mode - enableTranslationboolean Auto-translate non-English prompts truepromptUpsamplingboolean AI prompt enhancement falsesafetyToleranceinteger Content moderation level 2callBackUrlstring Webhook notification URL - uploadCnboolean Use China servers for upload falsewatermarkstring Watermark identifier -
Next Steps
Support
Need help? Here are your options:
Technical Support : support@kie.ai
API Status : Monitor service health and announcements
Documentation : Explore detailed API references
Community : Join our developer community for tips and examples
Ready to create amazing AI images? Start with the examples above and explore the full API capabilities!