Bulk generation
Bulk AI image generation with the Midjourney API
How to generate hundreds or thousands of Midjourney images from a CSV file through an API, without hitting queue limits, with retries that make sense and a run you can restart. A complete Python script included.
Published
Product photos for a catalog, ten ad variants for every product, a cover for each blog post: at some point one prompt at a time is not enough, and you want to give a script a spreadsheet and come back to a folder of images.
Sending the requests is the easy part. The hard part is that Midjourney only runs a few jobs at a time per account and rejects the rest, some prompts fail no matter how often you resend them, and a run of a thousand images will be interrupted at least once. This article walks through how to handle all three, and ends with a Python script you can run as it is.
The limit is Midjourney, not the API
Every image is generated on a Midjourney account, and each plan caps how many jobs run at once. From Midjourney's plan comparison, as of November 2026:
| Plan | Images at once | Queued jobs | Fast GPU time | Relax mode for images |
|---|---|---|---|---|
| Basic, $10 | 3 Fast | 10 | 3.3 h/month | No |
| Standard, $30 | 3 Fast or Relax | 10 | 15 h/month | Unlimited |
| Pro, $60 | 12 Fast or 3 Relax | 10 | 30 h/month | Unlimited |
| Mega, $120 | 12 Fast or 3 Relax | 10 | 60 h/month | Unlimited |
What this means for a batch:
- Send only as many tasks as the account can run. Jobs over the limit wait in Midjourney's queue, and once that queue is full the next task fails with "Your job queue is full". Firing 500 requests at once gives you a few images and a lot of errors.
- Fast hours run out. When they do, tasks fail with "You've run out of hours". On Standard and above you can switch the account to Relax with the
speedmethod and keep going. Relax is unlimited, but it is slower. - More accounts means more images at once. Add several Discord accounts to the same API key, and requests without
account_hashare spread across them evenly. Three Standard accounts let you run 9 tasks at a time instead of 3.
How fast is that in practice? Across our users' Imagine tasks over the last 30 days, the median grid was ready in 36 seconds and 90% were ready within 88 seconds. With three tasks running at once, that is a rough ceiling of a few hundred grids an hour per Basic or Standard account in Fast mode, as long as the fast hours last.
What a robust batch does
- Keeps a fixed number of tasks in flight, three per Basic or Standard account, and starts the next one only when one finishes.
- Waits for each task by checking its status every 10 seconds. Status checks are free: only the task itself counts as a request.
- Retries only what can succeed on retry. A full queue or a Discord hiccup is temporary. A banned word or a wrong parameter will fail again, so it is written down instead of retried.
- Saves each image as soon as it is ready, as a file. Result links point to Discord's CDN, which is not permanent storage.
- Can be restarted. Results go to a CSV file row by row, and the next run skips what is already done.
The script
You need Python 3.8 or newer and the requests package (pip install requests). Put your prompts in prompts.csv with an id and a prompt column:
id,promptsneaker-white,a white sneaker on a concrete floor soft studio light --ar 4:5mug-beans,a ceramic mug with coffee beans top view --ar 1:1lamp-desk,a brass desk lamp on a walnut table warm evening light --ar 3:2
Midjourney parameters go into the prompt as in Discord. If a prompt contains commas, wrap it in double quotes, as usual in CSV.
Then run:
USERAPI_KEY=your-key python bulk_generate.py prompts.csv
For several accounts on one key, raise the number of tasks in flight: IN_FLIGHT=9 for three Standard accounts.
"""Generate Midjourney images for every prompt in a CSV file.Usage: USERAPI_KEY=your-key python bulk_generate.py prompts.csvprompts.csv needs an "id" and a "prompt" column. Images go to ./images,results are appended to results.csv, and a second run skips the rows thatare already done."""import csvimport osimport sysimport threadingimport timefrom concurrent.futures import ThreadPoolExecutor, as_completedimport requestsAPI = "https://api.userapi.ai/midjourney/v2"HEADERS = {"api-key": os.environ["USERAPI_KEY"]}IN_FLIGHT = int(os.environ.get("IN_FLIGHT", "3")) # 3 per Basic/Standard accountPOLL_EVERY = 10 # seconds between status checksTASK_TIMEOUT = 15 * 60 # give up on a task after 15 minutesRETRIES = 2 # extra attempts for temporary failuresOUT_DIR = "images"RESULTS = "results.csv"# status_reason fragments worth a retry: the queue was full or Discord hiccuped.# Anything else (banned prompt, bad parameter, no fast hours) fails the same way again.TEMPORARY = ("job queue is full", "queue full", "slow down", "invalidated","an error occurred while send", "discord gateway")lock = threading.Lock()def start(prompt: str) -> str:for attempt in range(4):try:r = requests.post(f"{API}/imagine", json={"prompt": prompt}, headers=HEADERS, timeout=30)if r.ok:return r.json()["hash"]if r.status_code < 500: # a bad request will not get better on retryraise RuntimeError(f"HTTP {r.status_code}: {r.text[:200]}")except (requests.ConnectionError, requests.Timeout):passtime.sleep(5 * 2 ** attempt) # 5, 10, 20, 40 sraise RuntimeError("could not start the task")def wait(task_hash: str) -> dict:deadline = time.time() + TASK_TIMEOUTwhile time.time() < deadline:time.sleep(POLL_EVERY)try:r = requests.get(f"{API}/status", params={"hash": task_hash}, headers=HEADERS, timeout=30)r.raise_for_status()except requests.RequestException:continue # a failed status check is not a failed tasktask = r.json()if task["status"] in ("done", "error"):return taskreturn {"status": "error", "status_reason": "timed out on our side", "hash": task_hash}def download(url: str, path: str) -> None:with requests.get(url, stream=True, timeout=120) as r:r.raise_for_status()with open(path, "wb") as f:for chunk in r.iter_content(1 << 16):f.write(chunk)def generate(row: dict) -> dict:reason = ""for attempt in range(RETRIES + 1):try:task = wait(start(row["prompt"]))except RuntimeError as e:return {"id": row["id"], "status": "error", "hash": "", "file": "", "reason": str(e)}if task["status"] == "done":path = os.path.join(OUT_DIR, f"{row['id']}.png")try:download(task["result"]["url"], path)except requests.RequestException as e:return {"id": row["id"], "status": "error", "hash": task["hash"], "file": "", "reason": f"download: {e}"}return {"id": row["id"], "status": "done", "hash": task["hash"], "file": path, "reason": ""}reason = task.get("status_reason") or ""if not any(t in reason.lower() for t in TEMPORARY):breaktime.sleep(30 * (attempt + 1))return {"id": row["id"], "status": "error", "hash": task.get("hash", ""), "file": "", "reason": reason}def save(result: dict) -> None:with lock:new = not os.path.exists(RESULTS)with open(RESULTS, "a", newline="") as f:w = csv.DictWriter(f, fieldnames=["id", "status", "hash", "file", "reason"])if new:w.writeheader()w.writerow(result)print(result["id"], result["status"], result["reason"])def main(csv_path: str) -> None:os.makedirs(OUT_DIR, exist_ok=True)done = set()if os.path.exists(RESULTS):with open(RESULTS, newline="") as f:done = {r["id"] for r in csv.DictReader(f) if r["status"] == "done"}with open(csv_path, newline="") as f:rows = [r for r in csv.DictReader(f) if r["prompt"].strip() and r["id"] not in done]print(f"{len(rows)} prompts to generate, {IN_FLIGHT} at a time")with ThreadPoolExecutor(max_workers=IN_FLIGHT) as pool:for future in as_completed(pool.submit(generate, row) for row in rows):save(future.result()) # written as soon as each image is readyif __name__ == "__main__":main(sys.argv[1])
How it works, part by part:
startcreates the task and returns its hash. If our API cannot be reached or answers with a 5xx, it waits 5, 10, 20 and 40 seconds between attempts. A 4xx means the request itself is wrong, so it is not retried.waitchecks the status every 10 seconds until the task isdoneorerror. One failed check doesn't fail the task. After 15 minutes it gives up and records a timeout.generateretries a task at most twice, and only whenstatus_reasonsays the queue was full or the request didn't reach Discord. It downloads the finished image toimages/<id>.png.mainrunsIN_FLIGHTtasks at a time and appends each result toresults.csvas soon as it is ready, so stopping the script with Ctrl+C loses nothing that is already finished.
Run it again after it stops, or after you fix prompts that failed. Rows with status done in results.csv are skipped, failed ones are tried again.
We tested the script against a stub API that fails on purpose: a 502 on the first request, a full queue on the first attempt, an invalid parameter, an empty row and a bad request. The temporary failures were retried and succeeded, the permanent ones were written to results.csv once, no more than IN_FLIGHT tasks ran at the same time, and a second run picked up only the unfinished rows.
Single images instead of grids
Imagine returns one file with a grid of four pictures. If you need each picture separately, upscale the ones you want. Upscale takes the grid's hash and a choice from 1 to 4, and it is fast: most upscales over the same 30 days were done in 2 to 3 seconds. Keep in mind that every upscale is a request of its own, so four upscales per grid make five requests per prompt instead of one. The details are in the upscale guide.
That is why results.csv keeps the hash of every grid. You can pick the best pictures after the batch and upscale only those, without generating anything again.
What fails, and how often
Over the last 30 days, about one Imagine task in ten ended with an error. Of those failed tasks:
| Share of failures | Reason | What to do |
|---|---|---|
| 30% | Invalid prompt parameters, such as a value Midjourney doesn't accept or two parameters that don't work together | Test a few rows before the whole batch. Retrying doesn't help |
| 24% | No active Discord account on the key | Check the account in the dashboard: the token may have expired |
| 12% | The task never got an answer from Midjourney | Retry it |
| 10% | A problem with the Midjourney subscription, such as a paused payment | Fix it in your Midjourney account |
| 9% | Too many jobs at once on the account | Lower IN_FLIGHT or add accounts |
The rest are smaller: a failed send to Discord, moderation, a blocked account, a captcha. The script's TEMPORARY list covers the cases where a retry makes sense. Before a big batch, run the first five or ten rows: a wrong parameter repeated in every prompt is the most expensive mistake you can make.
Webhooks for very large batches
For tens of thousands of images, polling means a lot of open loops. Instead, pass webhook_url with each task, and we POST the result to your server when it is ready. Put the row id into callback_id, and it comes back with the result, so you know which row to update. The webhook body is the same JSON as the status response. Examples of a webhook receiver are in the Python guide.
You still need to keep the number of tasks in flight under the account limit: the webhook only replaces the waiting part.
Without code
If the prompts live in Google Sheets and you use n8n, the same batch works without a script: rows go through a loop, the images go to Google Drive and every row gets its status and link. The walkthrough is in AI image generation in n8n.
What it costs
Every task is one request. On pay-per-request that is $0.04, so 1,000 grids cost $40. The monthly plan is $25 per Discord account with no request limit, which is cheaper from 625 requests a month on. Status checks are free, and your Midjourney subscription is paid separately. The first 50 requests are free, which is enough to test the script on a small CSV. The details are on the pricing page.
Try it on 50 free requests
Register, add a Discord account that has Midjourney, and you get an API key. The first 50 requests are free and you don’t need to enter a card. Since 2023 more than 10,000 people have signed up and sent over 8 million requests through the API.