Welcome to Midjourney API

The Midjourney API enables you to generate high-quality AI images using the power of Midjourney’s advanced AI models. Whether you’re building an app, automating workflows, or creating content, our API provides simple and reliable access to AI image generation.

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/mj/generate" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "taskType": "mj_txt2img",
    "prompt": "A majestic mountain landscape at sunset with snow-capped peaks",
    "speed": "relaxed",
    "aspectRatio": "16:9",
    "version": "7"
  }'

Step 2: Check Task Status

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

Response Format

Successful Response:
{
  "code": 200,
  "msg": "success",
  "data": {
    "taskId": "mj_task_abcdef123456"
  }
}
Task Status Response:
{
  "code": 200,
  "msg": "success",
  "data": {
    "taskId": "mj_task_abcdef123456",
    "successFlag": 1,
    "resultInfoJson": {
      "resultUrls": [
        {"resultUrl": "https://example.com/image1.jpg"},
        {"resultUrl": "https://example.com/image2.jpg"},
        {"resultUrl": "https://example.com/image3.jpg"},
        {"resultUrl": "https://example.com/image4.jpg"}
      ]
    }
  }
}

Generation Types

Generate images from text descriptions:
{
  "taskType": "mj_txt2img",
  "prompt": "A futuristic cityscape with flying cars and neon lights",
  "aspectRatio": "16:9",
  "version": "7"
}

Generation Speeds

Choose the right speed for your needs:

Relaxed

Free tier optionSlower generation but cost-effective for non-urgent tasks

Fast

Balanced optionStandard generation speed for most use cases

Turbo

Premium speedFastest generation for time-critical applications

Key Parameters

prompt
string
required
Text description of the desired image. Be specific and descriptive for best results.Tips for better prompts:
  • Include style descriptors (e.g., “photorealistic”, “watercolor”, “digital art”)
  • Specify composition details (e.g., “close-up”, “wide angle”, “bird’s eye view”)
  • Add lighting information (e.g., “golden hour”, “dramatic lighting”, “soft natural light”)
aspectRatio
string
Output image aspect ratio. Choose from:
  • 1:1 - Square (social media)
  • 16:9 - Widescreen (wallpapers, presentations)
  • 9:16 - Portrait (mobile wallpapers)
  • 4:3 - Standard (traditional displays)
  • And 7 other ratios
version
string
Midjourney model version:
  • 7 - Latest model (recommended)
  • 6.1, 6 - Previous versions
  • niji6 - Anime/illustration focused
stylization
integer
Artistic style intensity (0-1000):
  • Low values (0-100): More realistic
  • High values (500-1000): More artistic/stylized

Complete Workflow Example

Here’s a complete example that generates an image and waits for completion:
class MidjourneyAPI {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.baseUrl = 'https://api.kie.ai/api/v1/mj';
  }
  
  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 (!response.ok || result.code !== 200) {
      throw new Error(`Generation failed: ${result.msg || 'Unknown error'}`);
    }
    
    return result.data.taskId;
  }
  
  async waitForCompletion(taskId, maxWaitTime = 600000) { // Max wait 10 minutes
    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.resultInfoJson;
          
        case 2:
          const taskError = status.errorMessage || 'Task generation failed';
          console.error('Task generation failed:', taskError);
          if (status.errorCode) {
            console.error('Error code:', status.errorCode);
          }
          throw new Error(taskError);
          
        case 3:
          const generateError = status.errorMessage || 'Task created successfully but 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 30 seconds before checking again
      await new Promise(resolve => setTimeout(resolve, 30000));
    }
    
    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;
  }
  
  async upscaleImage(taskId, index) {
    const response = await fetch(`${this.baseUrl}/upscale`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        taskId,
        index
      })
    });
    
    const result = await response.json();
    if (!response.ok || result.code !== 200) {
      throw new Error(`Upscale failed: ${result.msg || 'Unknown error'}`);
    }
    
    return result.data.taskId;
  }
}

// Usage example
async function main() {
  const api = new MidjourneyAPI('YOUR_API_KEY');
  
  try {
    // Text-to-image generation
    console.log('Starting image generation...');
    const taskId = await api.generateImage({
      taskType: 'mj_txt2img',
      prompt: 'A majestic ancient castle perched on a misty mountain peak, golden sunset light illuminating the stone walls',
      speed: 'fast',
      aspectRatio: '16:9',
      version: '7',
      stylization: 500
    });
    
    // Wait for completion
    console.log(`Task ID: ${taskId}. Waiting for completion...`);
    const result = await api.waitForCompletion(taskId);
    
    console.log('Image generation successful!');
    console.log('Generated images count:', result.resultUrls.length);
    result.resultUrls.forEach((urlInfo, index) => {
      console.log(`Image ${index + 1}: ${urlInfo.resultUrl}`);
    });
    
    // Upscale the first image
    console.log('\nStarting upscale of first image...');
    const upscaleTaskId = await api.upscaleImage(taskId, 1);
    
    const upscaleResult = await api.waitForCompletion(upscaleTaskId);
    console.log('Image upscale successful!');
    console.log('Upscaled image:', upscaleResult.resultUrls[0].resultUrl);
    
  } catch (error) {
    console.error('Error:', error.message);
  }
}

main();

Async Processing with Callbacks

For production applications, use callbacks instead of polling:
{
  "taskType": "mj_txt2img",
  "prompt": "A serene zen garden with cherry blossoms",
  "callBackUrl": "https://your-app.com/webhook/mj-callback",
  "aspectRatio": "16:9"
}
The system will POST results to your callback URL when generation completes.

Learn More About Callbacks

Complete guide to implementing and handling Midjourney API callbacks

Best Practices

Status Codes

200
Success
Task created successfully or request completed
400
Bad Request
Invalid request parameters or malformed JSON
401
Unauthorized
Missing or invalid API key
402
Insufficient Credits
Account doesn’t have enough credits for the operation
429
Rate Limited
Too many requests - implement backoff strategy
500
Server Error
Internal server error - contact support if persistent

Task Status Descriptions

successFlag: 0
Generating
Task is currently being processed
successFlag: 1
Success
Task completed successfully
successFlag: 2
Failed
Task generation failed
successFlag: 3
Generation Failed
Task created successfully but generation failed

Image Storage and Retention

Generated image files are retained for 15 days before deletion. Please download and save your images within this timeframe.
  • Image URLs remain accessible for 15 days after generation
  • Plan your workflows to download or process images before expiration
  • Consider implementing automated download systems for production use

Next Steps

Support

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

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