Midjourney has no official public API, so what you actually integrate with is usually a third-party wrapper service. Paths, fields, and state machines differ from vendor to vendor, but the underlying flow is similar: submit a task and get an ID, poll the status, download the image on success, then upscale or create variations as needed. This article follows that chain, focusing on the differences that cause trouble and on compliance boundaries.

Trademark note: Midjourney is a trademark of Midjourney, Inc.; Discord is a trademark of Discord Inc. This article is for technical explanation only and implies no partnership, agency, or endorsement. Midjourney currently offers no official API, and the terms and stability of third-party interfaces must be verified independently.

1. Choose the Vendor Before Writing Code

Third-party Midjourney interfaces have no common standard. Even for the same "submit a task" action, some return task_id while others return job_id; some use /imagine, others /v1/midjourney/imagine; some make upscales and variations separate tasks, while others expose action endpoints. Before choosing, confirm six things:

  • Whether the authentication method and base URL are stable, and whether paths are versioned.
  • Which task types are supported: text-to-image, upscale, variation, redraw, blend, and describe.
  • The status field and terminal-state enumeration, and whether success, failure, moderation rejection, and timeout are distinguished.
  • Result retention time and download limits, and whether callbacks are supported.
  • Concurrency, queueing, and rate-limit rules, and whether failures are billed.
  • The vendor's continuity and exit mechanisms, and whether short contracts and data deletion are available.

The closer the interface shape is to your existing system, the lower the migration cost. Do not judge from demo output alone; read the error-code documentation and the task-query capabilities first.

2. Authentication and Request Conventions

The common approach is an API key in a request header with a JSON body. The exact header field depends on the vendor's documentation; typical forms include Authorization: Bearer, X-API-Key, or a custom header. Put the key, base URL, and timeout into configuration instead of scattering them through the code.

Confirm three things before calling: whether the environment is test or production, whether the key is bound to an IP or quota, and whether requests pass through a corporate egress proxy. Many 401 and 403 responses are not wrong keys but misconfigured environments or proxies rewriting request headers.

3. Submitting a Task: Prompt and Parameters

A typical submission request is shown below; the fields are examples only:

export MJ_API_KEY="your-provider-key"
export MJ_BASE_URL="https://provider.example.com"

curl -sS -X POST "$MJ_BASE_URL/v1/midjourney/imagine" \
  -H "Authorization: Bearer $MJ_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "minimalist product photo of a ceramic cup, soft window light --ar 4:3",
    "aspect_ratio": "4:3",
    "callback_url": "https://api.example.com/callbacks/mj"
  }'

Whether prompt parameters such as --ar, --v, and --style are passed through intact varies by vendor. Some split aspect ratio into a separate field, while others parse the prompt directly. Do not assume a parameter took effect; after submission, verify it against the returned task details.

As soon as submission succeeds, write the task ID, business reference number, prompt, parameters, submission time, and operator into your task table. Polling, retries, reconciliation, and cost allocation all depend on this record.

4. Polling: State Machine and Backoff

Status Meaning Suggested handling
queued Waiting in queue Keep waiting; avoid duplicate submissions
running Generating Poll with a backoff strategy
succeeded Success Read the result and copy it immediately
failed Failure Record the error code and decide whether to retry
moderated Moderation rejection Revise the prompt; do not retry unchanged
expired Timeout or expired link Check task details and resubmit if needed

Start polling at 3 to 5 seconds, back off gradually to 15 to 30 seconds, and set a total timeout. Do not poll once per second, and do not let multiple instances query the same task at once. Stop polling once a task reaches a terminal state, and persist the final status and result URL.

If the vendor supports webhooks, you can use them as the primary notification, but you must verify signatures, enforce idempotency, and keep scheduled polling as a fallback. Lost callbacks are not uncommon in wrapper services.

5. Downloading and Re-Storing

The image URL returned after a successful task usually expires: it may last minutes or days, or be a temporary signed URL. Do not write it directly into a frontend page or deliver it to a customer.

The correct order is: on receiving the success status, download immediately, copy the file to your own object storage, record the task ID, object path, file size, checksum, and download time, then write the internal address into your business database. Set timeouts, retries, and a concurrency cap for downloads; for large images, use a server-side proxy to avoid browser cross-origin issues and link leakage.

Midjourney usually returns a four-image grid plus upscaled single images. When storing, name grid images and upscales separately and keep the original task ID so later variations or redraws can be matched correctly.

6. Upscales, Variations, and Redraws

Upscales and variations usually depend on the original task ID and an image index. A common call is to submit a new task with task_id and index, or to call the vendor's action endpoint. Whether indexing starts at 1 or 0 is not consistent across vendors; confirm with a test task before integrating.

A few practical suggestions:

  • Record "original task" and "derived task" as a parent-child relationship to avoid upscaling the same image twice.
  • A variation may produce a new four-image grid and is billed as a new task; estimate the cost before running batches.
  • Redraw, inpainting, and blend are not supported by every vendor; rely on the documentation.
  • Upscaled images may still be subject to upstream link expiry, so copy them immediately after success.

7. Rate Limits, Concurrency, and Cost

A wrapper's throughput depends on its account pool and upstream queue; it is not equal to the concurrency you purchased. Common limits include tasks per minute, simultaneously running tasks, and a daily quota per account. On a 429, lower concurrency and apply exponential backoff; do not retry blindly.

Calculate cost by "successfully delivered images," not by submissions. Include failures, moderation rejections, duplicate submissions, and upscale variations in the denominator to get the true per-image cost. Run a small batch first, confirm the success rate and average latency, and then scale up gradually.

8. Common Errors and Troubleshooting

  • 401: missing key, malformed key, environment mismatch, or an invalid upstream account.
  • 403: IP not on the allowlist, insufficient quota, or permissions not enabled.
  • 404: wrong path or task ID, or the task may have been cleaned up.
  • 429: rate limit triggered; reduce concurrency and back off.
  • 5xx: upstream or wrapper failure; use an idempotency key to confirm nothing was created, then retry.
  • Task failed: read the error code and distinguish parameter, moderation, and upstream failures.
  • Link 403/404: the result URL expired or requires authentication; go back to the task details and fetch it again.

Log request IDs, task IDs, error codes, and masked parameters. Wrapper services often re-wrap error messages, so keeping the raw response can significantly shorten troubleshooting time.

9. Migration Checklist

When moving from one vendor to another, or from a self-hosted proxy to a managed service, confirm each item below:

  1. Whether the base URL, authentication header, and request paths are replaced as a set.
  2. Whether the task ID field name, status enumeration, and terminal-state logic match.
  3. Whether prompt parameters are passed through or split into fields, and whether --ar and --v take effect.
  4. Whether the calling method and index rules for upscales, variations, and redraws match.
  5. Whether result-link lifetime, download limits, and storage logic have been verified.
  6. Whether callbacks are supported, and whether signature verification and idempotency are complete.
  7. Whether rate limits, concurrency, timeouts, and retries have been load-tested again.
  8. Whether billing rules, failure refunds, and invoice reconciliation line up.

After migration, run a batch of real business samples and compare success rate, average latency, and per-image cost before switching all traffic. Do not cut over at once without reconciliation and rollback plans.

FAQ

Does the Midjourney API return images synchronously?

Usually not. Submitting a task returns only a task ID; you need to poll or wait for a callback, then download the image after success. Designing around a synchronous interface easily leads to timeouts and duplicate submissions.

How long does a task usually need to be polled?

It depends on the queue and upstream load; tens of seconds to several minutes is common. Start at 3 to 5 seconds, back off gradually, and set a total timeout. After a timeout, check task details rather than resubmitting immediately.

Vendors differ widely; links may last minutes, hours, or days. In production, do not depend on upstream links; copy the image to your own object storage immediately after success.

How do I call upscales and variations?

Generally you need the original task ID plus an image index, then submit a derived task or call an action endpoint. Index origin and field names differ by vendor, so confirm with a single test task first.

What should teams in China pay attention to?

First confirm network reachability, cross-border data flow, and content compliance, then assess the vendor's terms and shutdown risk. If you need a unified entry point, you can register with the ZSQH AI Gateway and check the model pricing page for currently supported models; do not treat a non-OpenAI-protocol image interface as directly compatible.

Next Steps

First run one low-complexity prompt through all four steps: submit, poll, download, and store. Then add upscales, variations, and callbacks. When choosing a vendor, put compliance and exit mechanisms ahead of output quality. If you need to manage multiple model entry points in one place, register with the ZSQH AI Gateway and check the model pricing page for available models and billing methods.

Related reading: