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
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.midapi.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.midapi.ai/api/v1/mj/record-info?taskId=YOUR_TASK_ID" \
-H "Authorization: Bearer YOUR_API_KEY"
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
Text-to-Image
Image-to-Image
Image-to-Video
Generate images from text descriptions: {
"taskType" : "mj_txt2img" ,
"prompt" : "A futuristic cityscape with flying cars and neon lights" ,
"aspectRatio" : "16:9" ,
"version" : "7"
}
Transform existing images with text prompts: {
"taskType" : "mj_img2img" ,
"prompt" : "Transform this into a cyberpunk style" ,
"fileUrl" : "https://example.com/source-image.jpg" ,
"aspectRatio" : "1:1" ,
"version" : "7"
}
Create videos from static images: {
"taskType" : "mj_video" ,
"prompt" : "Add gentle movement and atmospheric effects" ,
"fileUrl" : "https://example.com/source-image.jpg" ,
"version" : "7"
}
Generation Speeds
Choose the right speed for your needs:
Relaxed Free tier option Slower generation but cost-effective for non-urgent tasks
Fast Balanced option Standard generation speed for most use cases
Turbo Premium speed Fastest generation for time-critical applications
Key Parameters
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”)
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
Midjourney model version:
7 - Latest model (recommended)
6.1, 6 - Previous versions
niji6 - Anime/illustration focused
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.midapi.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 ( ' \n Starting 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 ();
import requests
import time
class MidjourneyAPI :
def __init__ ( self , api_key ):
self .api_key = api_key
self .base_url = 'https://api.midapi.ai/api/v1/mj'
self .headers = {
'Authorization' : f 'Bearer { api_key } ' ,
'Content-Type' : 'application/json'
}
def generate_image ( self , ** options ):
response = requests.post( f ' { self .base_url } /generate' ,
headers = self .headers, json = options)
result = response.json()
if not response.ok or result.get( 'code' ) != 200 :
raise Exception ( f "Generation failed: { result.get( 'msg' , 'Unknown error' ) } " )
return result[ 'data' ][ 'taskId' ]
def wait_for_completion ( self , task_id , max_wait_time = 600 ):
start_time = time.time()
while time.time() - start_time < max_wait_time:
status = self .get_task_status(task_id)
success_flag = status[ 'successFlag' ]
if success_flag == 0 :
print ( "Task is generating, continue waiting..." )
elif success_flag == 1 :
print ( "Generation completed successfully!" )
return status[ 'resultInfoJson' ]
elif success_flag == 2 :
task_error = status.get( 'errorMessage' , 'Task generation failed' )
print ( f "Task generation failed: { task_error } " )
if status.get( 'errorCode' ):
print ( f "Error code: { status[ 'errorCode' ] } " )
raise Exception (task_error)
elif success_flag == 3 :
generate_error = status.get( 'errorMessage' , 'Task created successfully but generation failed' )
print ( f "Generation failed: { generate_error } " )
if status.get( 'errorCode' ):
print ( f "Error code: { status[ 'errorCode' ] } " )
raise Exception (generate_error)
else :
print ( f "Unknown status: { success_flag } " )
if status.get( 'errorMessage' ):
print ( f "Error message: { status[ 'errorMessage' ] } " )
time.sleep( 30 ) # Wait 30 seconds
raise Exception ( 'Generation timeout' )
def get_task_status ( self , task_id ):
response = requests.get( f ' { self .base_url } /record-info?taskId= { task_id } ' ,
headers = { 'Authorization' : f 'Bearer { self .api_key } ' })
result = response.json()
if not response.ok or result.get( 'code' ) != 200 :
raise Exception ( f "Status check failed: { result.get( 'msg' , 'Unknown error' ) } " )
return result[ 'data' ]
def upscale_image ( self , task_id , index ):
data = {
'taskId' : task_id,
'index' : index
}
response = requests.post( f ' { self .base_url } /upscale' ,
headers = self .headers, json = data)
result = response.json()
if not response.ok or result.get( 'code' ) != 200 :
raise Exception ( f "Upscale failed: { result.get( 'msg' , 'Unknown error' ) } " )
return result[ 'data' ][ 'taskId' ]
# Usage example
def main ():
api = MidjourneyAPI( 'YOUR_API_KEY' )
try :
# Text-to-image generation
print ( 'Starting image generation...' )
task_id = api.generate_image(
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
print ( f 'Task ID: { task_id } . Waiting for completion...' )
result = api.wait_for_completion(task_id)
print ( 'Image generation successful!' )
print ( f 'Generated images count: { len (result[ "resultUrls" ]) } ' )
for i, url_info in enumerate (result[ 'resultUrls' ]):
print ( f 'Image { i + 1 } : { url_info[ "resultUrl" ] } ' )
# Upscale the first image
print ( ' \n Starting upscale of first image...' )
upscale_task_id = api.upscale_image(task_id, 1 )
upscale_result = api.wait_for_completion(upscale_task_id)
print ( 'Image upscale successful!' )
print ( f 'Upscaled image: { upscale_result[ "resultUrls" ][ 0 ][ "resultUrl" ] } ' )
except Exception as error:
print ( f 'Error: { error } ' )
if __name__ == '__main__' :
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
Be specific and descriptive in your prompts
Include style, mood, and composition details
Use artistic references when appropriate
Test different prompt variations to find what works best
Use “relaxed” speed for non-urgent tasks
Monitor your credit usage regularly
Implement request batching where possible
Set up usage alerts in your application
Always check the response status code
Implement exponential backoff for retries
Handle rate limiting gracefully
Log errors for debugging and monitoring
Status Codes
Task created successfully or request completed
Invalid request parameters or malformed JSON
Missing or invalid API key
Account doesn’t have enough credits for the operation
Too many requests - implement backoff strategy
Internal server error - contact support if persistent
Task Status Descriptions
Task is currently being processed
Task completed successfully
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!