# MegaPotato AI image upscaler API: developer documentation

Image upscaling (super-resolution) over REST. MegaPotato is an AI image upscaler (https://megapotato.app) built on its own super-resolution model: it enlarges photos and AI art ×2, ×4 or ×8 in one pass, up to 16 400 px on the long side, or refines them at the same size (×1). The REST API runs the same model at the same per-photo prices as the site, pay as you go, no subscription.

- Human-readable docs with live prices: https://megapotato.app/developers
- OpenAPI 3.1: https://megapotato.app/developers/openapi.json
- Code examples (curl, Python, Node.js): https://github.com/MegaPotato-AI/megapotato-api-examples
- ComfyUI node: https://registry.comfy.org/nodes/comfyui-megapotato (source: https://github.com/MegaPotato-AI/comfyui-megapotato)
- Benchmark of 18 AI upscalers (October 2026, open data): https://megapotato.app/blog/best-ai-image-upscalers-2026
- Site index for language models: https://megapotato.app/llms.txt
- Keys: https://megapotato.app/account#api · Prices: https://megapotato.app/pricing · Support: support@megapotato.app

## The model in two calls

1. `POST /v1/upscale` — send the photo and the factor; the job is accepted at once and the price (`cost_chips`) is held from your balance.
2. `GET /v1/jobs/{id}?wait=55` — the server holds the request until the job finishes (up to 55 s); the answer carries `result_url`, a download link valid for about an hour.

Base URL `https://megapotato.app`. Every request carries `Authorization: Bearer $MEGAPOTATO_API_KEY`.

## Quickstart

Create a key on the account page (https://megapotato.app/account#api), export it as `MEGAPOTATO_API_KEY`, then:

### curl

```bash
# 1. Send a photo
curl https://megapotato.app/v1/upscale \
  -H "Authorization: Bearer $MEGAPOTATO_API_KEY" \
  -H "Idempotency-Key: photo-001" \
  -F file=@photo.jpg \
  -F upscale=4
# → {"id": "6f6f4c1e-…", "status": "queued", "upscale": 4, "cost_chips": …}

# 2. Wait for it (the server holds the request up to 55 s)
curl "https://megapotato.app/v1/jobs/6f6f4c1e-…?wait=55" \
  -H "Authorization: Bearer $MEGAPOTATO_API_KEY"
# → {"status": "completed", "result_url": "https://…", …}

# 3. Download the PNG (plain GET, no auth header)
curl -o photo_x4.png "$RESULT_URL"
```

### Python

```python
import os, sys, time, requests

API = "https://megapotato.app/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['MEGAPOTATO_API_KEY']}"}

def call(method, path, headers=None, **kwargs):
    """One API call. Retries what can succeed later (429, 5xx, network), stops on everything else."""
    for attempt in range(8):
        try:
            r = requests.request(method, f"{API}{path}", headers={**HEADERS, **(headers or {})}, timeout=70, **kwargs)
        except (requests.ConnectionError, requests.Timeout):
            time.sleep(2 ** attempt)
            continue
        if r.status_code == 429 or r.status_code >= 500:
            time.sleep(float(r.headers.get("Retry-After", 2 ** attempt)))
            continue
        if not r.ok:  # other 4xx: fix the request, retrying won't help
            err = r.json()["error"]
            sys.exit(f"{r.status_code} {err['type']}: {err['message']}")
        return r.json()
    sys.exit("gave up after repeated temporary errors")

# Bytes, not an open file: every retry must send the whole photo again.
photo = open("photo.jpg", "rb").read()
job = call("POST", "/upscale", headers={"Idempotency-Key": "photo-001"},
           files={"file": ("photo.jpg", photo)}, data={"upscale": "4"})

# Always read the job at least once: a retried upload may already be finished, and only GET carries
# result_url / error.
while True:
    job = call("GET", f"/jobs/{job['id']}", params={"wait": 55})
    if job["status"] in ("completed", "failed"):
        break

if job["status"] == "completed":
    result = requests.get(job["result_url"], timeout=120)
    result.raise_for_status()
    open("photo_x4.png", "wb").write(result.content)
else:
    print(job["error"])
```

### Node.js

```js
// Save as upscale.mjs and run with Node 18+: node upscale.mjs
import { readFile } from "node:fs/promises"

const API = "https://megapotato.app/v1"
const headers = { Authorization: `Bearer ${process.env.MEGAPOTATO_API_KEY}` }
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))

// One API call. Retries what can succeed later (429, 5xx, network), stops on everything else.
async function call(path, init = {}) {
  for (let attempt = 0; attempt < 8; attempt++) {
    let res
    try {
      res = await fetch(`${API}${path}`, { ...init, headers: { ...headers, ...init.headers } })
    } catch {
      await sleep(2 ** attempt * 1000) // network error: try again
      continue
    }
    if (res.status === 429 || res.status >= 500) {
      await sleep(Number(res.headers.get("retry-after") ?? 2 ** attempt) * 1000)
      continue
    }
    const body = await res.json()
    if (!res.ok) throw new Error(`${res.status} ${body.error.type}: ${body.error.message}`)
    return body
  }
  throw new Error("gave up after repeated temporary errors")
}

const form = new FormData()
form.append("file", new Blob([await readFile("photo.jpg")]), "photo.jpg")
form.append("upscale", "4")

const { id } = await call("/upscale", { method: "POST", headers: { "Idempotency-Key": "photo-001" }, body: form })
// Always read the job at least once: a retried upload may already be finished, and only GET carries result_url / error.
let job
do {
  job = await call(`/jobs/${id}?wait=55`)
} while (job.status !== "completed" && job.status !== "failed")
console.log(job.status === "completed" ? job.result_url : job.error)
```

## Try it without a key

No account and no key: `POST /v1/try` takes the same multipart body (`file` + `upscale`, optionally `jpeg`) and runs a real job on the same model; `cost_chips` in the answer is what a key would pay, and nothing is charged. Poll it on `GET /v1/try/{id}?wait=55` (the job id is the only credential; `Idempotency-Key` is ignored on the trial). Trial jobs queue behind every keyed job, so they can wait longer when the service is busy. The trial is budgeted: a few jobs an hour per address, a shared ceiling for everyone and a size limit per job. Over a budget the answer is `429` with `Retry-After`; a photo over the size limit gets `422` with the price and the limit; while the trial is closed, the trial answers `403`. The current numbers are on https://megapotato.app/developers#try.

```bash
curl https://megapotato.app/v1/try -F file=@photo.jpg -F upscale=4
# → {"id": "6f6f4c1e-…", "status": "queued", "upscale": 4, "cost_chips": …}
curl "https://megapotato.app/v1/try/6f6f4c1e-…?wait=55"
# → {"status": "completed", "result_url": "https://…", …}
```

## Test keys

Any signed-in account can create a test key (`mp_test_…`) on the account page, before buying chips. A test key goes through the whole flow — uploads are checked and priced exactly like with a live key — but nothing runs and nothing is charged: every job comes back `completed` with a sample image in both `result_url` and `result_jpeg_url`, and `jpeg_status` is always `ready`, whether `jpeg=true` was sent or not. Live keys (`mp_live_…`) are created on the same page; new accounts start with free chips, and whether every signed-in account can create a live key at once or it unlocks with the first chip pack is a service setting, stated live on https://megapotato.app/developers#test-keys.

## Authentication

Send the key on every request as `Authorization: Bearer mp_live_…`. Keys are shown once when created; only a hash is stored. Keep them on your server, never in a mobile app, a web page or a repository; a leaked key is revoked on the account page and stops working immediately. Keys are never accepted in query parameters.

## Check the price — `POST /v1/quote`

JSON body `{"width": <px>, "height": <px>, "upscale": 1|2|4|8}` → `{"cost_chips": <n>, "output_width": <px>, "output_height": <px>, "upscale": <factor>}`. Free: nothing is uploaded, held or charged. The price grows with the size of the result; the live figures for two example photos are on https://megapotato.app/developers#pricing, and chip packs are on https://megapotato.app/pricing (chips never expire).

```bash
curl https://megapotato.app/v1/quote \
  -H "Authorization: Bearer $MEGAPOTATO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"width": 4032, "height": 3024, "upscale": 2}'
```

## Upscale a photo — `POST /v1/upscale`

Multipart form: `file` (PNG, JPEG, WebP or HEIC, up to 40 MiB) and `upscale`: `1` (refine, same size), `2`, `4` or `8`. The input may be up to 6 000 px on its long edge; the result may be up to 16 400 px per side — so ×4 takes inputs up to 4 100 px and ×8 up to 2 050 px. Over-limit requests are rejected before any pixel work and never charged.

Optional `jpeg`: `true` adds a full-size JPEG of the result (quality 92, no chroma subsampling) next to the PNG, at no extra cost; default `false`. A lossless 16K PNG can weigh several hundred MB, the JPEG of the same result usually a small fraction of that. The job then carries `result_jpeg_url` and `jpeg_status` (see below).

Response `200`: `{"id": "<uuid>", "status": "queued", "upscale": 4, "cost_chips": <n>}`. `cost_chips` is held from the balance at submit, captured when the result is delivered and refunded automatically if the job fails or is cancelled: you pay only for results you receive.

Always send an `Idempotency-Key` header (1–128 characters, unique per photo). Repeating the request with the same key returns the same job and charges once, so a client-side timeout is always safe to retry. Reusing a key with a different image, `upscale` or `jpeg` is a `422`.

## Get the result — `GET /v1/jobs/{id}`

`?wait=N` (0–55) holds the request until the job reaches a terminal state or the budget runs out. Status lifecycle: `queued → running → completed | failed` (a cancelled job reports `failed` with an explanatory `error`). Treat an unknown status as non-terminal and keep polling.

```json
{
  "id": "6f6f4c1e-…",
  "status": "completed",
  "result_url": "https://…",
  "error": null,
  "upscale": 4,
  "created_at": "2026-09-15T10:00:00Z",
  "eta_seconds": null,
  "result_jpeg_url": null,
  "jpeg_status": null
}
```

- `result_url`: `null` until `completed`, then a presigned PNG download link valid for about an hour; fetch it with a plain GET and no `Authorization` header. Read the job again for a fresh link; results stay available for the retention period shown on https://megapotato.app/developers#jobs.
- `error`: `null` unless `failed`; when the chips were refunded the message says so.
- `eta_seconds`: an estimate while the job is queued or running; `null` when unknown or terminal.
- `result_jpeg_url`: the full-size JPEG of a job sent with `jpeg=true`, under the same rules as `result_url` (a presigned link valid for about an hour, `null` until `completed`); `null` otherwise. Test keys are the exception: the sample image, always.
- `jpeg_status`: `null` for a job sent without `jpeg=true`; otherwise `pending` while queued or running, and also on a `completed` job while the JPEG is still being uploaded — usually for seconds, in rare cases up to about an hour (`result_url` already works; poll again for `result_jpeg_url`), `ready` when `result_jpeg_url` is set, `unavailable` when the job completed without a JPEG (the PNG is still delivered), failed or expired. With a test key it is always `ready`, whether `jpeg=true` was sent or not.
- Only your own jobs are visible; any other id (malformed ones included) is a `404`.

Most photos are back in seconds. The first requests after a quiet period can take a couple of minutes while more capacity comes online; keep polling with `?wait=55`, there is nothing special to handle.

## Errors

Every error uses one envelope: `{"error": {"type": "<class>", "message": "<text>"}}`. Branch on `type`, never on the message.

| HTTP | `type` | When |
| --- | --- | --- |
| 400 | `invalid_request_error` | the image can't be decoded, or its size is over the limits |
| 401 | `authentication_error` | the key is missing, wrong or revoked |
| 402 | `insufficient_credits` | not enough chips for this photo (the message says how many are needed) |
| 404 | `invalid_request_error` | no such job, or not yours |
| 413 | `invalid_request_error` | the file is larger than the upload limit |
| 415 | `invalid_request_error` | unsupported image format |
| 422 | `invalid_request_error` | bad `upscale` or `jpeg`, missing `file`, or an `Idempotency-Key` reused for a different photo, `upscale` or `jpeg` |
| 429 | `rate_limit_error` | too many requests, or too many photos in progress at once; honour `Retry-After` |
| 422 | `content_not_allowed` | our automated content check blocked the image (see the Terms); nothing was charged |
| 429 | `spend_limit_reached` | today's API spending limit is reached; `Retry-After` = seconds to 00:00 UTC |
| 500 | `server_error` | our fault; retry polls freely, retry uploads with the same `Idempotency-Key` |
| 503 | `service_unavailable` | we can't accept images right now; nothing was charged; retry after `Retry-After` |

## Limits

- A cap on photos in progress at once per account; past it a new upload gets `429` and nothing is charged.
- A per-key cap on uploads per minute; status requests are more generous.
- A daily spending limit through the API (UTC day), so a leaked key can't drain a balance; the account page shows the default and lets you set a lower one.

The live values of all three are on https://megapotato.app/developers#limits.

## Retries

- Always send an `Idempotency-Key` with uploads.
- On `429` wait for `Retry-After`. On `5xx` or a network error retry with a growing pause (1 s, 2 s, 4 s, …). Other `4xx` errors will not succeed on retry: fix the request.
- Poll with `?wait=55` instead of calling every second.

## Beta and versioning

The API is in public beta: no uptime guarantee yet; planned changes are announced by email. Within `/v1` fields and error types are only added, never removed or renamed, so ignore fields you don't know. Breaking changes would ship as `/v2`, announced at least 90 days ahead.

## Acceptable use

Results belong to you. Use the API only for images you have the right to process; no illegal content, no sexual content involving minors, no intimate images of anyone without their consent. Accounts that break these rules or the Terms (https://megapotato.app/terms) are blocked. Abuse reports: abuse@megapotato.app. Questions: support@megapotato.app.

## For AI agents and coding assistants

- Endpoints: `POST /v1/upscale` (multipart `file` + `upscale` ∈ {1, 2, 4, 8}, optional `jpeg=true` for a full-size JPEG next to the PNG), `GET /v1/jobs/{id}?wait=55`, `POST /v1/quote` (JSON `width`, `height`, `upscale`). Base URL `https://megapotato.app`, header `Authorization: Bearer <key>`.
- Send `Idempotency-Key` on every upload; poll with `?wait=55`; download `result_url` with a plain GET (and `result_jpeg_url` when `jpeg_status` is `ready`; `pending` on a `completed` job means poll again).
- Price before uploading with `/v1/quote`; a job that fails is refunded.
- No key yet? `POST /v1/try` (multipart `file` + `upscale`) runs one real job inside a small hourly budget; poll `GET /v1/try/{id}?wait=55`. `403` means the trial is closed, `429` a budget (honor `Retry-After`).
- A test key (`mp_test_…`) exercises the whole flow without charging and returns a sample image. A live key is created on the account page: every signed-in account, or after the first chip pack — https://megapotato.app/developers#test-keys says which; new accounts start with free chips.
- Machine-readable spec: https://megapotato.app/developers/openapi.json. This file: https://megapotato.app/developers.md.
