API protocol
Current gateway integration workflows
Preview guide
Paste into an AI assistant to help with integration. Documentation and examples only; no real credentials.
Direct answerChoose workflows based on the current implementation and successful samples, including complete MJ U1 button upscaling.
Updated · Reviewed
Scope and selection
These workflows follow the current gateway routes, request structures and adapters. External documentation is only a comparison source. A visible model, registered route or HTTP 200 alone does not establish a successful operation.
The table lists workflows with successful samples. U1 button upscaling has its own action contract. Instructions for the old change path are unavailable; the two request formats are not interchangeable.
| Need | Integration | Boundary |
|---|---|---|
| Upscale the first MJ grid image | U1 button upscale | Successful source, genuine U1 button and an action-capable source channel |
| MJ strong variation or pan | Strong variation, pan | Use your own source task and its actual button |
| Retrieve multiple MJ tasks | Batch retrieval | Account-owned tasks; check every status |
| Generate music | Legacy Suno music | Use channel-supported parameters; lyrics examples are withheld pending acceptance |
| Retrieve legacy Suno results | Single, batch, feed GET, feed POST | Gateway task envelope, not an upstream song array |
| Legacy key usage lookup | Lookup by key | Key in path plus owner ID; do not log the credential-bearing URL |
Complete MJ button workflow
Obtain your own successful source task with MJ Imagine. The example uses only the ordinary /mj prefix and U1. Keep source task, token mode and channel compatible. It does not create the source image or substitute unsupported buttons. A missing or ambiguous U1 stops the workflow instead of inventing a customId or falling back to change.
- Query the source using an inference key for the same account and require
status=SUCCESS. - Select the actual U1 from
buttons; submit its completecustomIdand the sourcetaskIdto/mj/submit/action. Omitmodel,actionandindex. - Save the returned task ID immediately. Poll with bounded backoff; require
SUCCESS,action=UPSCALEand a validimageUrlbefore consuming the result. - Retrieve media without the gateway API key. Verify a decodable image rather than a JSON error or expired link.
Runnable Python example
Python 3 standard library only. Save the code as midjourney_button_upscale.py. Set local environment variables GATEWAY_ORIGIN (the HTTPS gateway origin without /v1), API_KEY and SOURCE_TASK_ID, then run python3 midjourney_button_upscale.py.
The program prints RESUME_TASK_ID immediately after acceptance. Set it on a subsequent run to query without another submission. If submission times out without a task ID, investigate task/request records before retrying. The polling budget is ten minutes, with a separate 120-second timeout for each HTTP request.
"""Gateway MJ U1 workflow. Set GATEWAY_ORIGIN, API_KEY and SOURCE_TASK_ID.
Set RESUME_TASK_ID instead of SOURCE_TASK_ID to query an accepted job without
submitting again. A timed-out POST must be investigated before any retry.
"""
import json
import os
import time
from urllib.parse import quote, urlsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener
class NoRedirect(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
def run(base, key, source_id="", resume_id="", emit=print):
base = base.rstrip("/")
origin = urlsplit(base)
if (origin.scheme not in ("http", "https") or not origin.netloc
or origin.path or origin.query or origin.fragment
or origin.username or origin.password):
raise ValueError("GATEWAY_ORIGIN must be the gateway origin without a path")
if origin.scheme != "https" and origin.hostname not in ("localhost", "127.0.0.1", "::1"):
raise ValueError("Use HTTPS for a remote gateway")
if not key or not (resume_id or source_id):
raise ValueError("API_KEY and SOURCE_TASK_ID or RESUME_TASK_ID are required")
opener = build_opener(NoRedirect())
def request(path, payload=None):
headers = {"Authorization": "Bearer " + key, "Content-Type": "application/json"}
body = None if payload is None else json.dumps(payload).encode()
# No redirects with credentials, and no automatic POST retries.
with opener.open(Request(base + path, data=body, headers=headers), timeout=120) as response:
value = json.load(response)
if not isinstance(value, dict) or value.get("error"):
raise RuntimeError("Gateway returned an invalid or error response")
if "code" in value and str(value["code"]) not in ("1", "21", "22"):
raise RuntimeError(value.get("description") or "MJ request failed")
return value
def query(task_id):
task = request("/mj/task/" + quote(task_id, safe="") + "/fetch")
if task.get("id") != task_id or not isinstance(task.get("status"), str):
raise RuntimeError("Task response has a missing or mismatched ID/status")
return task
task_id = resume_id
if not task_id:
source = query(source_id)
if source["status"] != "SUCCESS":
raise RuntimeError("Source task must be SUCCESS before selecting its U1 button")
buttons = source.get("buttons")
if not isinstance(buttons, list):
raise RuntimeError("Source task does not provide action buttons")
matches = [button["customId"] for button in buttons
if isinstance(button, dict)
and button.get("label") == "U1"
and isinstance(button.get("customId"), str)
and button["customId"].startswith("MJ::JOB::upsample::1::")]
if len(matches) != 1:
raise RuntimeError("Source task must provide exactly one genuine U1 button")
submitted = request("/mj/submit/action", {"taskId": source_id, "customId": matches[0]})
task_id = submitted.get("result")
if str(submitted.get("code")) not in ("1", "21", "22") or not isinstance(task_id, str) or not task_id:
raise RuntimeError("Submission was not accepted with a valid task ID")
emit("RESUME_TASK_ID=" + task_id, flush=True)
deadline = time.monotonic() + 600
delay = 2
while time.monotonic() < deadline:
task = query(task_id)
if task["status"] == "FAILURE":
raise RuntimeError(task.get("failReason") or "MJ task failed")
if task["status"] == "SUCCESS":
result = task.get("imageUrl")
if task.get("action") != "UPSCALE" or not isinstance(result, str):
raise RuntimeError("Task did not return an UPSCALE image result")
image = urlsplit(result)
if image.scheme not in ("http", "https") or not image.netloc:
raise RuntimeError("Task returned an invalid image URL")
# Retrieve this media separately; never forward the gateway API key.
return {"task_id": task_id, "image_url": result}
time.sleep(delay)
delay = min(delay * 2, 15)
raise TimeoutError("Polling timed out; resume with RESUME_TASK_ID=" + task_id)
if __name__ == "__main__":
result = run(os.environ["GATEWAY_ORIGIN"], os.environ["API_KEY"],
os.environ.get("SOURCE_TASK_ID", ""), os.environ.get("RESUME_TASK_ID", ""))
print(json.dumps(result, ensure_ascii=False))
Excluded scenarios
Legacy Completions, other unaccepted MJ actions, Seed retrieval, Sora Remix, Qwen Omni, legacy Suno concat and audio URL upload still need their own channel prerequisites and acceptance. Ordinary chat is not substituted for Omni, v2 success is not evidence for legacy Suno, and button upscale success does not establish other actions.
Evidence boundary
The November 8, 2026 live U1 sample completed submission, SUCCESS retrieval and full PNG decoding. The new example also receives local request and failure-flow checks. This does not establish all models, accounts, modes or channels. Before production integration, validate submission, terminal state, output and usage on the intended account and channel.
Use cases
- Upscale using the U1 button of a successful source
- Resume retrieval after interruption and consume the result
API protocols
/mj/submit/action/mj/task/{task_id}/fetch
FAQ
Can I copy example task and button IDs?
No. Retrieve a successful source task owned by your account and use its actual U1 button. Stop when that button is unavailable.
Does successful submission mean the image is ready?
Submission returns a task ID. Query until SUCCESS, require UPSCALE and a valid imageUrl, then download and verify the image.
Can I rerun after a timeout?
Use RESUME_TASK_ID to query an accepted task. If submission timed out without an ID, inspect task and request records before creating again.
Does button upscale success establish other MJ actions?
No. U1 button upscaling has its own request contract and successful sample. Other actions require their own source task, button and channel capability; follow the corresponding reference.
Related guides
Official sources
- new-api · QuantumNous Official
兔子API