Welcome to 4o Image API

The 4o Image API, powered by the advanced GPT-4o model, provides high-quality AI image generation services. Whether you need text-to-image generation, image editing, or image variants, our API meets all your creative needs.

Authentication

All API requests require authentication using a Bearer token. Get your API key from the API Key Management Page.
Keep your API key secure and never share it publicly. If compromised, reset it immediately.

API Base URL

https://api.kie.ai

Authentication Header

Authorization: Bearer YOUR_API_KEY

Quick Start Guide

Step 1: Generate Your First Image

Start with a simple text-to-image generation request:
curl -X POST "https://api.kie.ai/api/v1/gpt4o-image/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, photorealistic style",
    "size": "1:1",
    "nVariants": 1
  }'

Step 2: Check Task Status

Use the returned task ID to check the generation status:
curl -X GET "https://api.kie.ai/api/v1/gpt4o-image/record-info?taskId=YOUR_TASK_ID" \
  -H "Authorization: Bearer YOUR_API_KEY"

Response Format

Successful Response:
{
  "code": 200,
  "msg": "success",
  "data": {
    "taskId": "task_4o_abc123"
  }
}
Task Status Response:
{
  "code": 200,
  "msg": "success",
  "data": {
    "taskId": "task_4o_abc123",
    "status": "SUCCESS",
    "response": {
      "result_urls": [
        "https://example.com/generated-image.png"
      ]
    }
  }
}

Core Features

Text-to-Image

Generate high-quality images from text descriptions:
{
  "prompt": "A cute orange cat sitting on a rainbow, cartoon style, bright colors",
  "size": "1:1",
  "nVariants": 2,
  "isEnhance": false
}

Image Editing

Edit existing images using masks and prompts:
{
  "filesUrl": ["https://example.com/original-image.jpg"],
  "maskUrl": "https://example.com/mask-image.png",
  "prompt": "Replace the sky with a starry night sky",
  "size": "3:2"
}

Image Variants

Generate creative variants based on input images:
{
  "filesUrl": ["https://example.com/base-image.jpg"],
  "prompt": "Keep main elements, change to watercolor painting style",
  "size": "2:3",
  "nVariants": 4
}

Image Size Support

Three standard image ratios are supported:

1:1

SquarePerfect for social media posts, avatars, product displays

3:2

LandscapeIdeal for landscape photos, desktop wallpapers, banners

2:3

PortraitGreat for portraits, mobile wallpapers, poster designs

Key Parameters

prompt
string
Text description for image generation. Provide detailed, specific descriptions for better results.Prompt Tips:
  • Describe main objects and scenes
  • Specify artistic styles (e.g., “photorealistic”, “cartoon”, “watercolor”)
  • Add color and lighting descriptions
  • Include mood and atmosphere elements
size
string
required
Image aspect ratio, required parameter:
  • 1:1 - Square
  • 3:2 - Landscape
  • 2:3 - Portrait
filesUrl
array
Input image URL list, supports up to 5 images. Supported formats: .jpg, .jpeg, .png, .webp, .jfif
maskUrl
string
Mask image URL to specify areas for editing. Black areas will be modified, white areas remain unchanged.
nVariants
integer
Number of image variants to generate. Options: 1, 2, or 4. Default is 1.
isEnhance
boolean
Prompt enhancement option. For specific scenarios like 3D image generation, enabling this can achieve more refined effects. Default is false.
enableFallback
boolean
Enable fallback mechanism. Automatically switches to backup models when the main model is unavailable. Default is false.

Complete Workflow Example

Here’s a complete example for image generation and editing:
class FourOImageAPI {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.baseUrl = 'https://api.kie.ai/api/v1/gpt4o-image';
  }
  
  async generateImage(options) {
    const response = await fetch(`${this.baseUrl}/generate`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(options)
    });
    
    const result = await response.json();
    if (result.code !== 200) {
      throw new Error(`Generation failed: ${result.msg}`);
    }
    
    return result.data.taskId;
  }
  
  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.status === 'SUCCESS') {
        return status.response;
      } else if (status.status === 'CREATE_TASK_FAILED' || status.status === 'GENERATE_FAILED') {
        throw new Error(`Generation failed: ${status.status}`);
      }
      
      // Wait 10 seconds before next check
      await new Promise(resolve => setTimeout(resolve, 10000));
    }
    
    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;
  }
  
  async getDownloadUrl(imageUrl) {
    const response = await fetch(`${this.baseUrl}/download-url`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ imageUrl })
    });
    
    const result = await response.json();
    return result.data.downloadUrl;
  }
}

// Usage Example
async function main() {
  const api = new FourOImageAPI('YOUR_API_KEY');
  
  try {
    // Text-to-Image Generation
    console.log('Starting image generation...');
    const taskId = await api.generateImage({
      prompt: 'A futuristic cityscape with flying cars and neon lights, cyberpunk style',
      size: '1:1',
      nVariants: 2,
      isEnhance: true,
      enableFallback: true
    });
    
    // Wait for completion
    console.log(`Task ID: ${taskId}. Waiting for completion...`);
    const result = await api.waitForCompletion(taskId);
    
    console.log('Image generation successful!');
    result.result_urls.forEach((url, index) => {
      console.log(`Image ${index + 1}: ${url}`);
    });
    
    // Get download URL
    const downloadUrl = await api.getDownloadUrl(result.result_urls[0]);
    console.log('Download URL:', downloadUrl);
    
    // Image Editing Example
    console.log('\nStarting image editing...');
    const editTaskId = await api.generateImage({
      filesUrl: [result.result_urls[0]],
      prompt: 'Add beautiful rainbow in the sky',
      size: '3:2'
    });
    
    const editResult = await api.waitForCompletion(editTaskId);
    console.log('Image editing successful!');
    console.log('Edited image:', editResult.result_urls[0]);
    
  } catch (error) {
    console.error('Error:', error.message);
  }
}

main();

Advanced Features

Mask Editing

Use masks for precise image editing:
const editTaskId = await api.generateImage({
  filesUrl: ['https://example.com/original.jpg'],
  maskUrl: 'https://example.com/mask.png',
  prompt: 'Replace the masked area with a beautiful garden',
  size: '3:2'
});
Black areas in the mask image will be edited, white areas remain unchanged. The mask must match the original image dimensions.

Fallback Mechanism

Enable fallback mechanism for service reliability:
const taskId = await api.generateImage({
  prompt: 'Artistic concept design',
  size: '1:1',
  enableFallback: true,
  fallbackModel: 'FLUX_MAX' // or 'GPT_IMAGE_1'
});

Using Callbacks

Set up webhook callbacks for automatic notifications:
const taskId = await api.generateImage({
  prompt: 'Digital artwork',
  size: '1:1',
  callBackUrl: 'https://your-server.com/4o-callback'
});

// Your callback endpoint will receive:
app.post('/4o-callback', (req, res) => {
  const { code, data } = req.body;
  
  if (code === 200) {
    console.log('Images ready:', data.info.result_urls);
  } 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.

Task Status Descriptions

GENERATING
In Progress
Task is currently being processed
SUCCESS
Success
Task completed successfully
CREATE_TASK_FAILED
Creation Failed
Task creation failed
GENERATE_FAILED
Generation Failed
Image generation failed

Best Practices

Image Storage and Downloads

Generated images are stored for 14 days before automatic deletion. Download URLs are valid for 20 minutes.
  • Image URLs remain accessible for 14 days after generation
  • Use download URL API to solve cross-domain download issues
  • Download URLs expire after 20 minutes
  • Recommended to download and store important images locally

Next Steps

Support

Need help? Our technical support team is here to assist you.

Ready to start creating amazing AI images? Get your API key and begin creating today!