Python Tutorial
Midjourney API with Python — Complete Guide
Generate AI images with Midjourney programmatically using Python. This step-by-step tutorial covers job submission, result polling, and webhook callbacks — with working code examples you can copy and run immediately.
Prerequisites
- ✓ Python 3.7+
- ✓ A Midjourney API key — get one free here
- ✓
requestslibrary (pip install requests)
01
Install & Setup
# No SDK needed — uses the standard requests library pip install requests
02
Submit an Image Generation Job
import requests
API_KEY = "your_api_key_here"
BASE_URL = "https://api.midjourney-api.com"
response = requests.post(
f"{BASE_URL}/midjourney/v1/submit-jobs",
headers={"API-KEY": API_KEY},
json={
"prompt": "a futuristic city at sunset --ar 16:9 --niji 7",
"mode": "fast", # "fast" or "relaxed"
"timeout": 600 # seconds, default 600
}
)
data = response.json()
task_id = data["data"]["taskId"]
print(f"Job submitted! Task ID: {task_id}")03
Poll for the Result
import time
def wait_for_result(task_id, max_attempts=30, interval=10):
for attempt in range(max_attempts):
res = requests.post(
f"{BASE_URL}/midjourney/v1/job-status",
headers={"API-KEY": API_KEY},
json={"taskIds": [task_id]}
)
jobs = res.json()["data"]
job = jobs[0]
if job["status"] == 1: # 1 = success
print("Image URL:", job["image"])
return job
elif job["status"] == 2: # 2 = failed
print("Job failed")
return None
print(f"Attempt {attempt+1}: still processing...")
time.sleep(interval)
result = wait_for_result(task_id)04
Use Webhooks (Recommended)
# Submit job with a webhook URL — no polling required
response = requests.post(
f"{BASE_URL}/midjourney/v1/submit-jobs",
headers={"API-KEY": API_KEY},
json={
"prompt": "a serene mountain lake at dawn --ar 4:3",
"mode": "fast",
"hookUrl": "https://yourapp.com/webhook/midjourney"
}
)
# Your webhook endpoint will receive a POST request like:
# {
# "status": 0,
# "data": {
# "taskId": "MtAd7mCuc4YqK_a1iAQSW",
# "status": 1,
# "image": "https://cdn.midjourney.com/...",
# "images": ["https://cdn.midjourney.com/.../0_0.png", ...]
# }
# }API Reference
| Parameter | Type | Required | Description |
|---|---|---|---|
| prompt | string | Yes | The image prompt, supports all Midjourney params (--ar, --niji, etc.) |
| mode | string | No | "fast" or "relaxed". Default: "fast". Fast uses 2× quota. |
| hookUrl | string | No | Webhook URL to receive the result when generation completes. |
| timeout | integer | No | Job timeout in seconds. Range: 300–1200. Default: 600. |
Ready to Generate Your First Image?
Get your free API key and start generating AI images with Python in minutes.