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.
1

Get Your API Key

Visit the API Key Management Page to obtain your API key.
2

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 (result.code !== 200) {
      throw new Error(`Generation failed: ${result.msg}`);
    }
    
    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);
      
      if (status.successFlag === 1) {
        return status.response;
      } else if (status.successFlag === 2 || status.successFlag === 3) {
        throw new Error(`Generation failed: ${status.errorMessage || 'Unknown error'}`);
      }
      
      // 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}`, {
      headers: {
        'Authorization': `Bearer ${this.apiKey}`
      }
    });
    
    const result = await response.json();
    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('\nStarting 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:

Best Practices

Performance Optimization

  1. Use Callbacks: Set up webhook callbacks instead of polling for better performance
  2. Model Selection: Use flux-kontext-pro for standard tasks, flux-kontext-max for complex scenes
  3. Prompt Engineering: Use detailed, specific prompts for better results
  4. Image Preprocessing: Ensure input images are accessible and optimized
  5. Download Management: Download images promptly as they expire after 14 days
  6. 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

ParameterTypeDescriptionDefault
promptstringRequired. Text description for generation/editing-
aspectRatiostringOutput image aspect ratio16:9
modelstringflux-kontext-pro or flux-kontext-maxflux-kontext-pro
outputFormatstringjpeg or pngjpeg

Optional Parameters

ParameterTypeDescriptionDefault
inputImagestringURL for image editing mode-
enableTranslationbooleanAuto-translate non-English promptstrue
promptUpsamplingbooleanAI prompt enhancementfalse
safetyToleranceintegerContent moderation level2
callBackUrlstringWebhook notification URL-
uploadCnbooleanUse China servers for uploadfalse
watermarkstringWatermark 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!