Skip to content

A connection timeout does not necessarily mean OCR failed. Before submitting again, check the original request and recover its saved result. Use its request ID, or replay the identical submission with the same Idempotency-Key if you never received an ID.

Error Codes

All API errors return a consistent JSON envelope with an HTTP status code, error code, and human-readable message.

Error Response Format

Every error response follows this structure:

json
{
  "error": {
    "code": "invalid_request",
    "message": "Idempotency-Key header is required"
  }
}

Branch on error.code, not on the message text. The envelope has no type field, and errors do not always carry a request_id. The engine_rate_limited 429 adds a top-level retry_after_seconds; the per-key rate_limited 429 does not, so read its Retry-After header (engine warm-up sends none; its message gives the seconds).

An engine that runs and fails does not return this envelope. A synchronous POST /v1/ocr answers HTTP 202 with status: "refunded" and the engine's reason in provider_error, or HTTP 503 with status: "timeout", Retry-After: 30 and retry_after_seconds: 30. If the router had already sent its headers after about 60 seconds, a JSON timeout arrives as HTTP 202 with no Retry-After header: read status, http_status and retry_after_seconds from the body. There is no 502 provider_error code; a 502 you see comes from a proxy between you and us. See Billing on Errors for what a failed request costs.

Error Reference

StatusCodeDescription
400invalid_requestMissing Idempotency-Key, malformed JSON, a Content-Type other than application/json, an engine that exists but is switched off (message "engine is not available"), or a max_output_tokens or loop_guard value the engine does not accept (the message names the allowed range).
400unknown_engineThe engine ID is not in the catalog. The response carries a suggestions array of close matches. See GET /v1/engines for valid IDs.
400invalid_inputThe base64 input decodes to fewer than 64 bytes, too small to be a page. The upload was usually cut off; send the complete file.
400invalid_input_urlinput.url points at a private, local or cloud-metadata address. Use a publicly reachable URL.
400engine_unavailableThe engine is listed but not yet available (coming soon). Choose another engine.
400history_disabledmode async was sent while OCR history is off for your account. Use sync mode, or turn history on.
401authentication_errorNo Authorization header, a header that does not start with "Bearer ", a key that does not start with sk-, an unknown or revoked key, or an expired session token. The message says which.
402insufficient_balanceYour account balance is too low for this request. The message gives the amount required and available. Add credits to continue. A base64 PDF sent without page_count is refused whole when the balance cannot cover every page: the message gives the page count, the cost and how many pages the balance covers, so send a smaller page_count or add credits. Nothing is read or charged.
403insufficient_scopeA read-only API key was used for POST /v1/ocr, /v1/ocr/batch or engine warm-up. Use a full-access key.
404not_foundThe request ID or async job does not exist for your account, or the URL is not an API endpoint.
409idempotency_key_reusedThis Idempotency-Key was already used with a different request. Use a new key for a new document. The comparison is on the effective request (decoded base64 bytes, resolved engine, defaults applied), so different base64 line breaks or omitted default fields still replay the original result. A request first stored before 2026-09-29 has no fingerprint and replays even a changed request. Replayed text is only available while OCR history is retained; with history off keep the first response.
410result_not_retainedGET /v1/ocr/{request_id} for a request made while OCR history was off. The text and charge were only in the original response.
413payload_too_largeRequest body exceeds the 10 MB limit. The limit is on the JSON body, so base64 encoding leaves room for about 7.5 MB of file. Reduce image resolution, split the document, or send a URL.
422invalid_requestpdf_routing cannot be applied to this document. The message says why.
422unsupported_inputThe engine reads PDF files only and the input is not a PDF: base64 bytes without a PDF header, or an input.url ending in an image extension. Refused before any charge. A PDF-only fallback.engine gets the same code as a 400.
429rate_limitedMore than 300 requests in 60 seconds on this API key. Wait for the Retry-After header (seconds; engine warm-up sends none, its message gives the seconds), then retry with the same Idempotency-Key. Not charged.
429engine_rate_limitedThe engine you chose is at its own request or concurrency limit and its wait queue could not seat this request. Retry-After and retry_after_seconds say when to come back. Not charged.
429api_key_limit_reachedThis key has reached its configured monthly limit. No credits were charged. Use another key; the request count resets each UTC month, but a limit of zero keeps blocking new requests.
500internal_errorSomething went wrong on our end. A failure on our side is never charged. Retry with the same Idempotency-Key.
503engine_unavailableThe engine is not configured on this server. The request never reached an engine, so it is not charged. Try a different engine.
503request_hard_cappedThe request ran past the server's time limit and was abandoned. Check it with GET /v1/ocr/{request_id} or replay the same Idempotency-Key before submitting new work.

Less common codes: engine_batch_only (400, the engine runs only as a Workbench batch), invalid_provider and provider_not_served (400, see provider on the API reference), and invalid_webhook_url (400). A 503 with provider_policy_unavailable, history_unavailable, private_identity_unavailable, unavailable, callback_unavailable or job_unavailable means a check on our side failed before any engine ran; nothing is charged and any hold is refunded. After invalid_webhook_url, callback_unavailable or job_unavailable the attempt is stored as failed, so send it again with a new Idempotency-Key.

Requests with a goal add goal_requires_deposit (403), goal_attempt_limit (429, with Retry-After and retry_after_seconds), goal_hold_too_large and unsupported_goal (422), goal_not_supported (400 or 422) and goal_unavailable (503). All are refused before any charge.

Engine refused the page or returned no text

Some engines decline real, readable pages. Google Gemini's RECITATION filter, for example, blocks output that matches published or template text (a printed declaration, standard report wording). The response has status: "refunded" and provider_error gives the engine's reason. Sending the page to the same engine again gives the same result.

To have OpenOCR retry automatically, name a backup engine and the cases that should use it. Nothing is retried unless you ask. The cases are provider_refused, provider_empty, provider_timeout, engine_unavailable, output_limit_reached and output_loop; leave out on for the first two. A refusal or timeout without a fallback ends with a hint showing this field.

json
{
  "engine": "google-gemini-3.1-flash-lite",
  "input": { "type": "url", "url": "https://example.com/page.jpg" },
  "fallback": { "engine": "openrouter-qwen-qwen3.7-flash", "on": ["provider_refused"] }
}

The backup runs once. engine is the engine that produced the text, warning says why the first engine was skipped, and attempts lists every engine tried with its outcome and cost. Each attempt is billed as on its own: the refused attempt at what the provider charged us for it (often $0), the backup at its own price. A backup your balance cannot cover is skipped and you are refunded as usual. Or send "fallback": "similar" to let OpenOCR pick an engine from another vendor that scores within 5 points on our hard benchmark and costs the same or less per page; then you are never charged more than the engine you asked for. A file no engine can read (corrupt or unsupported) is not retried.

The answer ran out of room or got stuck repeating itself

Language models write within an output allowance. When a dense page needs more, the model stops partway: the response has status: "partial" and stop_reason: "output_limit_reached", the text written so far is in extracted_text, and output_limit says what to send next. A model that reasons before answering can spend the whole allowance thinking; that answer is empty (provider_empty) and carries the same output_limit object.

json
{
  "status": "partial",
  "stop_reason": "output_limit_reached",
  "extracted_text": "…the text written before the allowance ran out…",
  "output_limit": {
    "reason": "max_output_tokens",
    "max_output_tokens": 8192,
    "max_output_tokens_limit": 65536,
    "suggested_max_output_tokens": 16384,
    "loop": null
  }
}

Re-send the page with "max_output_tokens": 16384 (the suggested value), up to max_output_tokens_limit. When the attempt already had the engine's maximum, suggested_max_output_tokens is null: try an engine with a larger output limit.

When an answer ends in one short piece of text repeated over and over, OpenOCR stops it with stop_reason: "output_loop", returns the text before the repetition began, and names the repeated text in output_limit.loop.unit. A bigger allowance will not help. Try another engine, or send "loop_guard": false if your page really repeats that text.

Both are charged like any engine that ran: the provider's cost for the attempt, at cost (see Billing on Errors). The allowance is also the most one page can cost, and a raised allowance raises the upfront hold. Add output_limit_reached or output_loop to fallback.on to have a backup engine take over instead.

/api/usage Auth Migration (Deprecated Query Key)

The dashboard usage endpoint GET /api/usagenow prefers Authorization: Bearer <api_key>. Query-string auth via api_key=... is a deprecated fallback for older clients and should be removed from integrations.

bash
# Preferred
curl "https://open-ocr.com/api/usage?user_id=YOUR_USER_ID" \
  -H "Authorization: Bearer sk-ocr-your-api-key"

# Deprecated fallback (migration only)
# curl "https://open-ocr.com/api/usage?user_id=YOUR_USER_ID&api_key=sk-ocr-your-api-key"

Why migrate: query parameters can leak into proxy logs, browser history, analytics tools, and referrer headers.

Rate Limit Headers

POST /v1/ocr, POST /v1/ocr/batch, GET /v1/usage and POST /v1/engines/{engine_id}/warm share one limit of 300 requests per sliding 60 seconds per API key (per user for a signed-in session); a batch counts once. Responses from POST /v1/ocr and GET /v1/usage carry these headers; a batch sends them only on its 429, and warm sends none. Polling (GET /v1/ocr/{request_id}) and the public catalog endpoints are not limited and send none.

HeaderDescription
X-RateLimit-LimitMaximum requests allowed per window
X-RateLimit-RemainingRequests remaining in current window
X-RateLimit-ResetOn an allowed request, always 60 (the window length, not a countdown). On a 429, seconds until a slot frees.
Retry-AfterSeconds to wait. Sent on a rate_limited or engine_rate_limited 429, on the allowed request that used the last slot, and on a 503 timeout (30). Absent on monthly key-limit errors and on an engine warm-up 429.
bash
# Example rate limit headers:
X-RateLimit-Limit: 300
X-RateLimit-Remaining: 297
X-RateLimit-Reset: 60

Retry Strategy

Retry only transient failures: rate_limited and engine_rate_limited 429,500,502, and503. Do not retry api_key_limit_reached with this key now. Positive limits reset next UTC month; zero limits do not. Fix 400/401/402/403/404/409/410/413/422 before retrying.

  • Always send an Idempotency-Key for POST OCR calls.
  • Reuse the same key across retries of the same logical request.
  • Use exponential backoff with jitter (1s, 2s, 4s, up to 10s).
  • For a transient 429, prefer Retry-After if present.
python
import random
import time
import uuid
import requests

TRANSIENT = {429, 500, 502, 503}

def ocr_with_retry(payload, api_key, idempotency_key, max_retries=3):
    # A longer client wait does not extend server execution.
    # For longer jobs, send mode="async" and poll the returned request_id.
    for attempt in range(max_retries + 1):
        resp = requests.post(
            "https://api.open-ocr.com/v1/ocr",
            json=payload,
            headers={
                "Authorization": f"Bearer {api_key}",
                "Idempotency-Key": idempotency_key,
            },
            timeout=(5, 515),  # connect 5s, read 515s: above the 480s sync cap + 10s handler backstop; default cap is 240s
        )

        if resp.status_code == 429:
            try:
                error_code = resp.json().get("error", {}).get("code")
            except (ValueError, AttributeError):
                error_code = None  # proxy may return HTML
            if error_code == "api_key_limit_reached":
                return resp  # monthly key quota: backoff cannot make this key usable now
        if resp.status_code not in TRANSIENT:
            return resp

        if resp.status_code == 503 and resp.json().get("status") == "timeout":
            return resp  # stored timeout: the same key returns the same 503, so do not retry it

        if attempt == max_retries:
            return resp

        if resp.status_code == 429 and resp.headers.get("Retry-After"):
            delay = float(resp.headers["Retry-After"])
        else:
            delay = min(2 ** attempt, 10) + random.uniform(0, 0.25)

        time.sleep(delay)

    return resp

payload = {"engine": "mistral-mistral-ocr-4-1", "input": {"type": "url", "url": "https://example.com/doc.png"}}
api_key = "sk-ocr-your-api-key"
resp = ocr_with_retry(payload, api_key, str(uuid.uuid4()))

# Use it: HTTP 2xx only means the call completed. Check the body status.
body = resp.json()
if body.get("status") == "timeout":
    # A timed-out request replays as the same 503 for this key, forever. Report it, or start a
    # NEW attempt with a NEW Idempotency-Key. Never loop on the same key.
    raise RuntimeError("OCR timed out; retry with a NEW Idempotency-Key")
if not resp.ok:
    # Error envelope: {"error": {"code", "message"}} with no "status" field, for example
    # 409 idempotency_key_reused (the key was used with a different request).
    err = body.get("error", {})
    raise RuntimeError(f"HTTP {resp.status_code} {err.get('code')}: {err.get('message')}")
if body["status"] != "succeeded":
    raise RuntimeError(f"OCR ended as {body['status']}: {body.get('provider_error')}")
print(body["extracted_text"])

Common 4xx Remediation (copy/paste)

4xx errors mean the request must be corrected before retrying.

bash
# 400 invalid_request: verify required fields + valid engine ID
curl -X POST https://api.open-ocr.com/v1/ocr   -H "Authorization: Bearer sk-ocr-your-api-key"   -H "Idempotency-Key: $(uuidgen)"   -H "Content-Type: application/json"   -d '{
    "engine": "mistral-mistral-ocr-4-1",
    "input": {"type": "url", "url": "https://example.com/doc.png"}
  }'

# 401 authentication_error: use Authorization header, not query params
curl https://api.open-ocr.com/v1/usage   -H "Authorization: Bearer sk-ocr-your-api-key"

# 402 insufficient_balance: the message gives the amount required and available.
# Every successful OCR result carries remaining_balance; add credits at https://open-ocr.com/pricing

# 409 idempotency_key_reused: {"error":{"code":"idempotency_key_reused","message":"This Idempotency-Key was already used with a different request. Use a new key for a new document."}}
# Fix: generate a NEW key for every distinct document. Same key + same request replays the original result.
bash
# 413 payload_too_large: compress or resize before upload
convert input.png -resize 2000x2000\> -quality 85 output.jpg

# 400 invalid_input: the base64 decodes to under 64 bytes (a cut-off upload)
# A corrupt or unreadable file is not rejected up front: the request fails once it
# runs, and the response is status "refunded" with the reason in provider_error.
# Fix checklist:
# 1) Confirm MIME type matches actual file
# 2) Confirm base64 has no data: prefix
# 3) Try the same file via public URL to isolate encoding issues

Common 5xx Remediation (copy/paste)

5xx errors are usually transient. Retry with the same idempotency key, then fall back to another engine.

bash
API_KEY="sk-ocr-your-api-key"
IDEMPOTENCY_KEY="$(uuidgen)"

# First attempt on preferred engine
curl -X POST https://api.open-ocr.com/v1/ocr   -H "Authorization: Bearer $API_KEY"   -H "Content-Type: application/json"   -H "Idempotency-Key: $IDEMPOTENCY_KEY"   -d '{"engine":"mistral-mistral-ocr-4-1","input":{"type":"url","url":"https://example.com/doc.png"}}'

# If 502/503 persists after retries, switch to a fallback engine with a NEW key
curl -X POST https://api.open-ocr.com/v1/ocr   -H "Authorization: Bearer $API_KEY"   -H "Content-Type: application/json"   -H "Idempotency-Key: $(uuidgen)"   -d '{"engine":"local-easyocr","input":{"type":"url","url":"https://example.com/doc.png"}}'

Billing on Errors

One rule decides every case: calling a model through OpenOCR never costs you more than calling that provider directly would have. Everything below follows from it.

If the engine never ran, you are not charged

Invalid input, a bad API key, a rate limit, an engine that is unavailable or misconfigured, or any failure on our side — you pay nothing, and any provisional debit is refunded automatically. No model did any work, so there is nothing to bill.

If the engine ran and then failed, you pay the provider's cost for that attempt

This covers an engine that errored partway, timed out mid-generation, or returned output you cannot use. The provider bills us for the work their model did, and we pass that through at cost, with no markup. The initial estimate is not a billing cap. The charge can apply even when a call fails or returns no text.

We charge only what we can evidence

If no provider cost is evidenced when the failure is settled, there is no charge and any provisional debit is refunded. We never guess a charge. The charge is the cost_debited field of the original POST response (and cost_usd in the webhook). GET /v1/ocr/{request_id} repeats it only while OCR history is enabled; with history off it returns 410 result_not_retained. If credit is insufficient, the amount stays owed and is collected after a top-up. New requests are refused with 402 insufficient_balance once the balance is too low to cover them.

Successful requests are unchanged

Token-priced requests use the engine's published token rates and provider fees, with usage from all attempts included. The initial debit is an estimate. For language-model engines the output allowance (max_output_tokens) is the most one page can cost, so a long page that finishes is billed at its real token cost, and a raised allowance raises the upfront hold. Flat-priced engines continue to charge per page.

Worked example

You send one page to an engine quoted at $0.002 per page. The model generates most of a response, then the request times out before it returns usable text. The provider bills us $0.0004 for the tokens it produced. You are charged $0.0004 — not the $0.002 quote, and not zero. Had the same engine failed before the model started, or had we no provider charge on record for it, you would be charged $0.00.

Reading it off the response

On a failed request, cost_debited is the amount actually passed through — 0.0 when nothing is owed, and non-zero when the engine ran. You never have to infer the charge from your balance, and you do not need to watch for a new status: a charged failure reports the same status and error code it would have reported if it had cost you nothing, with provider_error describing what went wrong. That status is still "refunded" on a POST even when only part of the hold came back, so read cost_debited, not the word. When the charge is non-zero, warning says so, for example: "the engine ran and produced billable usage; you were charged the provider's cost for the attempt ($0.0004); actual usage may exceed the initial estimate".