Skip to content

API Reference

OCR request fields, examples, error codes, and authentication, with a guide to the Stratus region pipeline.

Base URL: https://api.open-ocr.com/v1·All endpoints →·Error reference →

Stratus: detect and read selected regions

Stratus uses /v1/stratus/capabilities, /v1/stratus/pipeline/quotes, and /v1/stratus/pipeline/jobs before detection and region selection. It accepts write-capable API keys and quotes the whole job before processing. Upload a source through Workbench, inspect the stage result, then select regions for Mistral OCR 4.1.

Stratus API walkthrough, complete JSON bodies, pricing and errors →

Authentication

All API requests require a Bearer API key in the Authorization header. Generate keys from your dashboard.

bash
# All authenticated requests require this header:
Authorization: Bearer sk-ocr-your-api-key

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

Request Parameters — POST /v1/ocr

ParameterTypeRequiredDescription
Idempotency-Key (header)stringYesSend a new unique value (for example a UUID) for each logical request, and reuse the SAME value when you retry that request so it is processed and billed once. Use a NEW value for a different payload: Reusing a key with a DIFFERENT request body returns 409 idempotency_key_reused; the same key with the same request (even with different base64 line breaks or omitted default fields) replays the original result. The comparison is on the effective request (decoded base64 bytes, resolved engine, defaults applied such as output_format json, mode sync and language en; an omitted page_count compares equal to page_count 1), not its spelling. A request first stored before 2026-09-29 has no fingerprint and replays even a changed request. The text is replayed only while OCR history is retained: with history off a replayed success has a null extracted_text and a warning that the text was not retained, so clients with history off must keep the first response. Use a fresh key for every distinct document. Without this header the call fails with 400 (Idempotency-Key header is required).
enginestringYesEngine ID, e.g. "mistral-mistral-ocr-4-1". See GET /v1/engines.
inputobjectYesThe document to process.
input.typestringYesEither "url" or "base64". Other values, including "file", are rejected.
input.urlstringIf type=urlPublic URL of the document (image or PDF).
input.data_base64stringIf type=base64Raw base64-encoded document data. Do not include a data: URI prefix (it is rejected as invalid base64).
input.mime_typestringNoMIME type hint for base64 input, e.g. "image/png".
options.language_hintsstring[]NoLanguage hints, e.g. ["eng", "fra"], honored by OpenOCR-hosted engines. Prefer settings.language.
options.detect_tablesbooleanNoEnable table detection where the engine supports it.
options.pdf_text_layerbooleanNoPDFs only. Default true: a page is answered from the PDF's own embedded text, at the PDF Text Layer price (0.01¢ a page) instead of the engine's, only when it has at least 50 words, no pictures, no form fields, stamps, signatures or drawings, no hidden or covered text, and a quick OCR check of the page agrees with that text. Every other page goes to your engine; a page with pictures or form fields is read by your engine with the embedded text alongside. metadata.text_layer says where each page's text came from. false sends every page to your engine; with pdf_routing it aliases an omitted mode to ocr, while explicit auto/file_text conflicts with false (400). pdf_routing can change the picture policy or force a page action. Also accepted as settings.pdf_text_layer. Not yet applied to PDFs over 20 pages on engines that cannot read PDFs directly.
options.pdf_text_readerstringNo"pdfium" (default), "poppler" or "pdfminer": which reader reads the embedded text for options.pdf_text_layer. Any other value is rejected with 400.
pdf_routingobjectNoPer-page PDF control on /v1/ocr (sync or async). Fields: mode (auto, ocr, file_text; default auto), needs_ocr (ocr, skip, error; default ocr), pictures (read, ignore, large; default read), ocr_engine (request engine only), overrides ([{pages: "1,3-5", action: "ocr" | "file_text" | "skip"}]; default []). Overrides win. needs_ocr skip/error applies to missing, hidden, covered, unreadable or complex-script text and failed OCR checks; picture, annotation, drawing and short-text pages still use OCR. Auto and file_text require the PDF text layer: detect_tables, document_context/transcription instructions, structure engines or an unavailable reader cause 422 before charging. mode ocr without overrides needs no text layer. page_count up to 1,000 and within the engine max_pages limit; most engines, including LLM engines, accept only one page. Over 20 pages on an image-only engine it runs as a background job (poll /v1/ocr/jobs/{job_id}/status). Not supported yet with native-PDF engines, serverless background processing, non-PDF input, settings.page_range, a different OCR engine, request-level fallback, or /v1/ocr/batch. Batch-only engines cannot use this endpoint. See /docs/pdf-routing for examples, pricing and errors.
fallback_enginestringNoDeprecated alias for pdf_routing.ocr_engine. Validated but has no effect without pdf_routing. With it, must name the request engine; a different engine is not supported yet (400).
scanned_handlingstringNoDeprecated alias for pdf_routing.needs_ocr: "skip" maps to skip, "fallback" to ocr, "error" to error. Validated but has no effect without pdf_routing. Conflicting alias values return 400. "fallback" without fallback_engine returns 422.
fallbackobject | string | booleanNoOpt-in retry on another engine; nothing is retried unless you send it. {"engine": "<engine id>", "on": [...]} retries once on the engine you name, only in the cases you list: provider_refused, provider_empty, provider_timeout, engine_unavailable, output_limit_reached, output_loop (default ["provider_refused", "provider_empty"]). That engine must pass the same checks as engine, or the request is a 400 before any charge. Each attempt is billed as on its own: a failed attempt at what the provider charged us for it (often $0), the fallback at its own price, so you can pay for both; attempts lists each one. "similar" (or true) instead retries once on an engine from a different vendor that scores within 5 points on our hard benchmark and costs the same or less per page, never charged above the engine you asked for. Default "off". Not available on /v1/ocr/batch, and not for a PDF over 20 pages on an image-only engine (it runs as a page-by-page job that cannot retry elsewhere): that is a 400 before any charge, so send 20 pages or fewer or leave fallback out. An enabled fallback retry cannot be combined with pdf_routing. The deprecated fallback_engine is an alias for pdf_routing.ocr_engine and has no effect without pdf_routing.
document_contextobjectNo{ type (up to 128 characters), description (up to 4,000) }, at least one. A hint about what the document is, for engines that take instructions (instruction_capabilities.document_context in GET /v1/engines; in practice language-model engines). It only helps read ambiguous text: the model is told not to summarize, translate, correct or invent. Any other engine returns 422 unsupported_document_context before any charge. On a PDF it turns off the text layer. Also allowed on batch items.
transcriptionobjectNo{ format ("plain_text" or "markdown"), instructions (up to 4,000 characters) }, at least one. Presentation rules for the transcript, on the same engines as document_context; any other engine returns 422 unsupported_transcription. Cannot be combined with goal. Also allowed on batch items.
goalobjectNo{ preset, prompt }, at least one. preset is transcribe (the default OCR task), describe_image, extract_tables, find_regions or understand_website; prompt is your own request (prompt plus document_context at most 4,000 characters). Anything but plain transcribe replaces the OCR task, so only engines whose instruction_capabilities.goal_prompt is true take it (otherwise 422). Sync only, one base64 PNG, JPEG or static WebP image (no URL, no PDF); not with fallback, fallback_engine, max_output_tokens, transcription, output_format text, the demo key or /v1/ocr/batch (400 or 422, before any charge). Only for accounts that have paid for credit by card or auto top-up: signup and courtesy credit do not count (403 goal_requires_deposit). It holds up to $0.25 up front (instruction_capabilities.goal_hold_usd; 422 goal_hold_too_large above that) and is billed on the tokens used. At most 5 goal requests in any 24 hours may end with no charge or still be running; the sixth gets 429 goal_attempt_limit with Retry-After.
max_output_tokensintegerNoOutput allowance for this request in tokens, for language-model engines only. Default: the engine's own allowance (16,384 for models that reason before answering, 8,192 for others, never more than the model allows). Raise it, up to the model's maximum, when a dense page comes back with stop_reason "output_limit_reached"; the response names a value worth retrying with in output_limit.suggested_max_output_tokens. A value outside 1,024 to that maximum, or on an engine that is not a language model, is a 400 that names the allowed range. The allowance is also the most one page can cost, and a raised allowance raises the upfront hold.
loop_guardbooleanNoLanguage-model engines only. Default true: an answer that ends in one short piece of text repeated over and over is stopped with status "partial" and stop_reason "output_loop", and you get the text before the repetition. Send false when your page really repeats that text; the output allowance still applies.
providerobjectNoChoose which company runs the model (additive, 2026-11-05). OpenRouter's shape: order (preferred hosts), only (allow list), ignore (deny list), allow_fallbacks (default true; false makes order restrictive). Up to 20 names per list, each up to 64 characters, spelled as in served_by. Not the same as fallback, which switches to a different engine. On a direct engine, a 400 (provider_not_served) names its single host if only omits it, ignore lists it, or order omits it while allow_fallbacks is false. With allow_fallbacks absent or true, order alone is a preference and the engine runs. See #provider.
settings.dpiintegerNoResolution hint, 72 to 1200.
settings.page_rangestringNoPage selection such as "1-3,5" for engines that support it (OCRmyPDF).
settings.detect_tablesbooleanNoSame as options.detect_tables.
settings.auto_rotatebooleanNoDefault true: before the engine reads it, each image or rendered PDF page found sideways or upside down is turned upright. No extra charge. Not done for engines that handle rotation themselves (AWS Textract, Google Document AI, Mistral OCR, Datalab), engines on our serverless GPU pool, or with a goal. false sends every page as received. Also accepted as options.auto_rotate. metadata.rotation reports { enabled, pages_checked, pages_rotated, rotated_pages: [{ page, degrees_clockwise, confidence, source }] }, or { enabled: false, reason }; text and markdown output get an X-OCR-Rotated-Pages header such as "2:90".
modestringNo"sync" (default) or "async". An async request returns 202 with status "processing", a request_id and a poll_url; poll GET /v1/ocr/{request_id} or set webhook_url.
webhook_urlstringNoWebhook URL for async results. Needs mode="async", except a PDF request of more than 20 pages (page_count over 20, or a longer base64 PDF sent without page_count) on an engine that cannot read PDFs directly, which runs in the background and sends it too. If your balance is too low for an explicit page_count and you did not send mode="async", the count is lowered to what your credits cover, and a lowered count of 20 or fewer runs synchronously: the result is in the response and no webhook is sent. Without page_count, a base64 PDF whose whole document your balance cannot cover is refused with 402 instead.
page_countintegerNoOptional cap on the pages read, from page 1. Leave it out and a PDF sent as base64 is read whole, up to the engine's limit (max_pages_per_request in GET /v1/engines), and charged per page read. If your balance cannot cover every page, the request is refused with 402 insufficient_balance before anything is read or charged; the message says how many pages your balance covers. A PDF sent by URL is not counted before it is read (nor is a PDF the router cannot parse in time), so without page_count only page 1 is read. Compare pages with pages_total in the response to see whether the whole document was processed.
output_formatstringNo"json" (default), "text" (plain text, markdown stripped), or "markdown" (a fixed header, then the engine output untouched; see Text and markdown output below). For text and markdown the response body is the text itself; see Text and markdown output below. With json, extracted_text is unchanged and extracted_text_plain is added when the plain version differs.
settingsobjectNoUnified engine settings — auto-mapped to each engine's native format.
settings.languagestringNoISO language code, e.g. "en", "ja", "zh". Default: "en".
native_settingsobjectNoEngine-specific passthrough params. Overrides unified settings on conflict.

Account provider rule

In Dashboard Settings, set companies that may process your documents, companies that must never process them, or both. Leave both lists empty to allow any company. Names are case-insensitive and must match theserved_by value shown as “Processed by” in your request history (for example, DeepInfra, Google AI Studio, or google).

This account rule applies to every request. Changes apply to new requests within about a minute. If a request also includes a provider object, its only list intersects with the account allow list, and its ignore list adds to the account deny list. A request can narrow the account rule, but cannot widen it.

Response Fields

ParameterTypeRequiredDescription
request_idstringAlwaysUnique request identifier.
statusstringAlways"queued" or "processing" while running. Terminal: "succeeded", "partial" (some text recovered: after a timeout only the preview is stored; when the output allowance or the loop check stopped the answer, see stop_reason), "failed" or "rejected". A POST response can also say "refunded" or "timeout"; GET reports those as "failed".
enginestringAlwaysEngine ID that processed the request.
served_bystring | nullOn resultsWhich company actually processed the document. For an OpenRouter engine this is the host OpenRouter used, spelled as OpenRouter spells it (for example "DeepInfra"), or "unknown" when OpenRouter did not say. For any other engine it is that engine's own vendor (for example "google" or "mistral"). engine names the engine that produced the text: the one you chose, unless a fallback you asked for ran (see attempts) or the engine you named was retired and its replacement ran (see replacement). served_by says which company ran it. It is null when the host is unknown or was not recorded (older requests, multi-page PDF jobs where pages can be served by different hosts, and requests that ended without a result). Also returned in async job status and result, batch items, GET /v1/ocr/{request_id} and an idempotent replay. Additive: nothing else changed.
metadata.served_by_pagesobject[]When recordedOrdered source-page processing states and observed hosts. Compare with metadata.source_pages_total. See Which host processed each PDF page? below.
metadata.source_pages_totalintegerWith served_by_pagesOriginal source-page count (1–2000), used to verify the page report is complete. Omitted with the array when unavailable.
stop_reasonstringWhen the answer stopped early"output_limit_reached" (the page needed more than the output allowance) or "output_loop" (the model got stuck repeating itself), with status "partial" and the text so far in extracted_text. See Errors: the answer ran out of room.
output_limitobjectWhen the output allowance or loop check stopped the answer{ reason (max_output_tokens or loop), max_output_tokens (the allowance used), max_output_tokens_limit (the engine's maximum), suggested_max_output_tokens (a bigger allowance worth retrying with, or null), loop ({ unit, repeats, start_char } or null) }. Also present on an empty answer from a model that spent its whole allowance thinking.
provider_errorstring | nullAlwaysWhat went wrong when status is not succeeded; null on success.
warningstringWhen applicableOne sentence the caller must see, for example why a failed request still has a non-zero cost_debited, that a fallback or a retired engine's replacement produced the text, or why a partial answer stopped.
replacementobjectWhen the engine you named was retired{ requested_engine, engine, reason (engine_retired), retired_at, note, switch_to }. The request ran on the replacement engine, at that engine's price, and engine names it. Such a response is always JSON, whatever output_format asked for. Change your engine to switch_to to stop seeing it.
attemptsobject[]When a fallback was involvedEvery engine tried, in order: { engine, outcome (succeeded, failed or skipped), error_code, cost_usd }. cost_usd is what that attempt cost you; the entries add up to cost_debited.
extracted_textstringOn successFull extracted text: the raw engine output.
extracted_text_previewstringOn successTruncated preview of extracted text.
pagesintegerOn successNumber of pages processed and billed. Not clamped to the document length.
pages_totalintegerWhen knownNumber of pages in the source document. Omitted when the router cannot tell (for example a single image URL). If it is larger than pages, only part of the document was processed: because of page_count or the engine's max_pages limit, or because a URL input is not counted before it is read.
warningsstring[]When applicableNon-fatal notes, for example "document has 3 pages; processed 1. A read stops at page_count when one is sent, and at the engine's max_pages; ..." Check it when you send a multi-page PDF.
extracted_text_plainstringWhen it differsPlain-text conversion of extracted_text (see Plain-text conversion rules). Present only for output_format json when it differs from extracted_text.
metadata.aws_textract.documentobjectWhen supplied by the configured provider operationNative Blocks with table CELL indices/spans, relationship IDs, KEY_VALUE_SET links and page geometry alongside unchanged extracted_text. DetectDocumentText does not become a table/form parser. Explicitly configured and priced AnalyzeDocument is required for those features.
metadata.gcp_document_ai.documentobjectWhen supplied by the configured processorNative text, page tables and formFields with text anchors, dimensions and page numbers. An OCR processor does not become a Form Parser. Source text is retained in this object so native anchors remain usable.
metadata.azure_doc_intel.documentobjectWhen supplied by the configured modelNative AnalyzeResult tables, keyValuePairs, document fields, content, pages, modelId and stringIndexType. Read does not become Layout or field extraction. IBM Docling separately returns metadata.docling.document.tables. Native document metadata is limited to 1 MiB; document_truncated replaces oversized documents. Structure is JSON metadata; use JSON or the retained JSON result endpoint to retrieve it.
metadata.page_documentsobjectWhen a PDF is rasterized and provider structure is supplied{ pages: [{ page_number, metadata }], document_truncated }. page_number is the original 1-based source PDF page; provider-local page numbers and coordinate units remain unchanged inside metadata. Failed/skipped pages have no entry. The aggregate is limited to 1 MiB; document_truncated is true if page entries were omitted. Available in sync, async job results and retained-result replay. As with extracted_text, retained retrieval depends on your OCR history setting.
metadata.text_layerobjectFor PDFs where the text layer runs{ enabled, reader, engine_id, price_per_page, pages_from_text_layer, pages_read_by_engine, pages: [{ page, source (text_layer, ocr, text_layer_and_ocr or skipped), reason, policy_action (file_text, ocr, both or skip) and policy_reason when pdf_routing plans pages, embedded_text when the page was read both ways, ocr_check { seen_not_embedded, embedded_not_seen, order, embedded_order } when the quick OCR check ran }] }. reason is one of: embedded_text (answered from the PDF), no_embedded_text, unreadable_embedded_text, complex_script (right-to-left or complex scripts such as Arabic, Hebrew, Indic or Thai), covered_text or invisible_text (text the page does not show), has_annotations (form fields, stamps, signatures), has_drawings, has_pictures (any picture), too_little_text (under 50 words), ocr_check_disagrees (the quick OCR reading differs from the embedded text), ocr_check_unavailable (the check could not finish in time) or engine_is_the_ocr_check (you chose the engine the check uses). pdf_routing reports pages_skipped; mode ocr without overrides skips the analysis and returns a minimal report (page, source ocr, policy_action ocr, policy_reason mode_ocr; no reason). No word positions: for those, call a PDF Text Layer engine directly (metadata.pdf_text). not_used_reason is set when every page went to your engine: engine_reads_whole_pdf (the engine reads PDFs whole and cannot skip pages), no_clean_text_pages, document_too_long (over 100 pages), page_count_mismatch, pdf_unreadable, text_layer_unavailable or text_layer_timeout. { enabled: false, reason } when it does not run for this request: turned_off_by_request, unknown_reader, reader_unavailable, caller_instructions, engine_returns_structure (engines whose tables, forms or Markdown plain text cannot replace) or detect_tables.
metadata.pdf_textobjectPDF Text Layer engines{ reader, pages_without_text, suspect_pages, document } when you call a PDF Text Layer engine directly. document is { unit: "pt", origin: "top-left", pages: [{ page, width, height, rotation, has_text, suspect, images, lines: [{ bbox, words: [{ text, bbox }] }] }] } with bbox [x0, y0, x1, y1] on the page as displayed; above 1 MB it is omitted with document_truncated: true. A PDF with no embedded text on any page read fails instead of returning empty text.
metadata.warningsstring[]When applicableLLM engines only: notes about the output, for example: possible duplicated trailing block: 12 lines. It is not copied to the single warning field or the X-OCR-Warning header.
metadata.possible_duplicateobjectWhen applicableLLM engines only: { lines, text } describing an exact trailing repeat. Text is never removed: the transcript stays intact and this is only a flag for you to review.
http_statusintegerWhen applicableOnly when a slow response was committed early: the HTTP status the response would have had, for example 200 on a completed success.
poll_urlstringAsync onlyPath to poll for the result, /v1/ocr/{request_id}. Returned with status "processing". For an image-only PDF over 20 pages on an engine without native PDF it is /v1/ocr/jobs/{job_id}/status instead; fetch the text from /v1/ocr/jobs/{job_id}/result (see the PDF routing page).
cost_debitednumberAlwaysCredits charged (USD). Non-zero on a failed request when the engine ran and the provider billed us for the attempt — see Billing on Failed Requests. 0.0 when nothing is owed.
provider_latency_msintegerOn successEngine processing time in milliseconds.
confidencenumberOn success (engine-dependent)OCR confidence score (0–1). Absent for engines that don't report confidence.
applied_settingsobjectOn successActual settings applied, including language mapping and native overrides.

Which host processed each PDF page?

JSON results can include metadata.served_by_pages entries with page_number, state and served_by. Compare the array length with metadata.source_pages_total: every original source page must appear once, in order from 1 through that count, including pages outside page_count. Reports are limited to 1–2000 source pages. Older results or unknown source-page counts may omit both fields.

The states are provider_success, provider_failed, text_layer, skipped, not_requested and unrecorded. Only provider_success can carry a host: the actual OpenRouter host or direct vendor. unknown means a successful OpenRouter reply did not name a usable host; null means host evidence is unavailable. Successful empty replies still record their host. Local PDF text extraction and pages never sent to a provider do not.

For a complete served_by_pages report, the document-level served_by names a host only when every source page has provider_success with the same recorded host; otherwise it is null. Native-PDF and older whole-document results can still carry served_by without a per-page report. That scalar alone does not identify each page's host. Do not use a host from one reported page to describe the whole document.

This additive field is JSON-only. For async jobs, read /result; progress /status keeps its existing scalar field without the page array. Existing history-off and expiry rules still apply: this does not restore deleted results. Text/markdown bodies, headers and ordinary webhooks do not include this array.

Examples

1 — Single page (URL input)

bash
curl -X POST https://api.open-ocr.com/v1/ocr \
  -H "Authorization: Bearer sk-ocr-your-api-key" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: req-$(uuidgen)" \
  -d '{
    "engine": "mistral-mistral-ocr-4-1",
    "input": {
      "type": "url",
      "url": "https://example.com/invoice.png"
    }
  }'

# 200 OK (status: "succeeded"; still read the status field, not only the HTTP code)
{
  "request_id": "req_abc123",
  "status": "succeeded",
  "engine": "mistral-mistral-ocr-4-1",
  "extracted_text": "Invoice #1042\nDate: 2026-02-28\nTotal: $42.00",
  "extracted_text_preview": "Invoice #1042...",
  "pages": 1,
  "cost_debited": 0.004,
  "provider_latency_ms": 148,
  "confidence": 0.94
}

2 — Multi-page PDF by URL, with page_count

bash
curl -X POST https://api.open-ocr.com/v1/ocr \
  -H "Authorization: Bearer sk-ocr-your-api-key" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: req-$(uuidgen)" \
  -d '{
    "engine": "mistral-mistral-ocr-4-1",
    "page_count": 3,
    "input": {
      "type": "url",
      "url": "https://example.com/report.pdf"
    }
  }'

# 200 OK (status: "succeeded"; still read the status field, not only the HTTP code)
{
  "request_id": "req_pdf456",
  "status": "succeeded",
  "engine": "mistral-mistral-ocr-4-1",
  "extracted_text": "Page 1 content...\n--- Page 2 ---\nPage 2 content...\n--- Page 3 ---\nPage 3 content...",
  "pages": 3,
  "cost_debited": 0.012,
  "provider_latency_ms": 820
}

2b — The same PDF as base64, without page_count

bash
# Omit page_count and every page of a base64 PDF is read, up to the engine's
# max_pages_per_request. A URL input is not counted first: send page_count with it.
# If your balance cannot cover every page you get 402 insufficient_balance and nothing is read.
# 200 OK (status: "succeeded"; still read the status field, not only the HTTP code)
{
  "request_id": "req_pdf457",
  "status": "succeeded",
  "engine": "mistral-mistral-ocr-4-1",
  "extracted_text": "Page 1 content...\n--- Page 2 ---\nPage 2 content...\n--- Page 3 ---\nPage 3 content...",
  "pages": 3,
  "pages_total": 3,
  "cost_debited": 0.012
}

3 — Specific engine with language setting

Language hints are honored by OpenOCR-hosted engines such as local-tesseract. Some engines, including Mistral OCR, ignore the hint and detect the language automatically.

bash
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": "local-tesseract",
    "input": {
      "type": "url",
      "url": "https://example.com/japanese-receipt.png"
    },
    "settings": {
      "language": "ja"
    }
  }'

# 200 OK (status: "succeeded"; still read the status field, not only the HTTP code)
{
  "request_id": "req_ja789",
  "status": "succeeded",
  "engine": "local-tesseract",
  "extracted_text": "領収書\n合計: ¥4,200",
  "pages": 1,
  "cost_debited": 0.002,
  "provider_latency_ms": 1420,
  "applied_settings": { "language": "ja" }
}

4 — Base64 image input

bash
# Encode image locally
IMAGE_B64=$(base64 -w 0 /path/to/receipt.png)

curl -X POST https://api.open-ocr.com/v1/ocr \
  -H "Authorization: Bearer sk-ocr-your-api-key" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: req-$(uuidgen)" \
  -d "{
    \"engine\": \"mistral-mistral-ocr-4-1\",
    \"input\": {
      \"type\": \"base64\",
      \"data_base64\": \"$IMAGE_B64\",
      \"mime_type\": \"image/png\"
    }
  }"

# 200 OK (status: "succeeded") — same response shape as URL input
Try it live
Run OCR on a document

Text and markdown output

With output_format set to text or markdown the body is text rather than JSON (for markdown, a fixed wrapper followed by the unchanged engine output, shown below), so page information travels in response headers (browsers can read all of them via CORS except X-OCR-Rotated-Pages, which the router does not expose):

ParameterTypeRequiredDescription
X-Request-IdstringAlwaysThe request_id, for GET /v1/ocr/{request_id}.
X-Cost-DebitednumberAlwaysWhat this request cost you, in USD (cost_debited).
X-Remaining-BalancenumberAlwaysYour balance after the request, in USD.
X-OCR-EnginestringAlwaysThe engine that produced the text.
X-OCR-WarningstringWhen applicableThe JSON warning field, for example why a failed request was still charged.
X-OCR-PagesintegerWhen pages were processedPages processed and billed.
X-OCR-Pages-TotalintegerWhen knownPages in the source document.
X-OCR-WarningsstringWhen applicableWarnings joined with " | ". The header is absent when nothing was skipped.
X-OCR-Rotated-PagesstringWhen a page was turnedpage:degrees pairs, for example "2:90,5:180" (see settings.auto_rotate).

These responses are HTTP 200 even when the engine failed: a failed request returns an empty text body (markdown: the wrapper with its Status line). Check X-Cost-Debited and X-OCR-Warning, or use JSON if you need the status. A timeout is the JSON 503 described below. A slow response whose headers were sent early cannot carry the X-OCR-* headers. A request to a retired engine always gets JSON, so the replacement notice is not lost.

text
# OCR Result

**Engine:** mistral-mistral-ocr-4-1
**Status:** succeeded

---

<engine output, exactly as the engine returned it>

Large PDF jobs may add a pages_failed array to the finished result, together with a warning such as "page 4 failed OCR". On an async 202, pages_total is known for base64 inputs only; for URL inputs it appears when you poll or receive the webhook. Text conversion rules are listed below. Batch items carry pages, pages_total and warnings. GET /v1/ocr/{request_id} returns them once the request has finished, including on replays. Text output text is plain text with markdown stripped; markdown returns a fixed header followed by the engine output, which is not modified:

provider: choose which company runs the model

Added 2026-11-05, and optional: requests without it behave exactly as before. Many models can be run by more than one company. Send provider on POST /v1/ocr (sync or async) or on a batch item to say which ones may handle your document. It uses the same shape as OpenRouter's provider object.

ParameterTypeRequiredDescription
provider.orderstring[]NoPreferred hosts to try first, in this order. On a direct engine, leaving its host out refuses the request only when allow_fallbacks is false.
provider.onlystring[]NoAllow list. No other host may run the request.
provider.ignorestring[]NoDeny list. These hosts never run the request.
provider.allow_fallbacksbooleanNoDefault true, as on OpenRouter. false makes order restrictive when you send it.
json
{
  "engine": "openrouter-qwen-qwen3-vl-30b-a3b-instruct",
  "input": { "type": "url", "url": "https://example.com/invoice.png" },
  "provider": { "only": ["DeepInfra", "Fireworks"], "allow_fallbacks": false }
}
  • Names must match the served_by values. served_by in the response (and in your history) tells you which host actually ran the request, spelled the way OpenRouter spells it (for example DeepInfra). Matching ignores upper and lower case. Each list holds at most 20 names of at most 64 characters; anything else is a 400 (invalid_provider).
  • Engines that go through OpenRouter pass your object to OpenRouter. Engines marked "don't train on my data" keep that rule on top of your choice; your choice can narrow it, never weaken it.
  • Direct engines (OpenAI, Google, Mistral, Datalab and our own servers) have one host, their vendor. The request is refused with a 400 (provider_not_served) if only is given without that host, ignore lists it, or order is given without it and allow_fallbacks is false. The error names the host; nothing is sent and nothing is charged. With allow_fallbacks absent or true, order alone is a preference, so the engine runs.
  • Charges are unchanged. You pay the real cost reported for the host that ran it.
  • Not the same as fallback. fallback retries on a different engine you allow; provider only limits which company runs the engine you chose, and a fallback engine whose host you excluded is skipped.
  • A provider choice is only used when you send it. It cannot be combined with fallback_engine.

HTTP status codes for OCR requests

  • A completed, successful synchronous request with the default JSON output returns 200 with status: "succeeded" in the body. Still check the status field, not only the HTTP code: a response can also carry partial, refunded or another non-success status. When a slow response was committed early (headers flushed before the result), a completed success is HTTP 202 with status: "succeeded" and http_status: 200 in the body, so do not treat every 202 as still running.
  • An engine that runs and fails is not an error envelope. With JSON output a partial result returns 200 with status: "partial", a failure returns 202 with status: "refunded" and the reason in provider_error, and a timeout returns 503 with status: "timeout", Retry-After: 30 and retry_after_seconds: 30. If the router had already sent its headers after about 60 seconds, the HTTP status is 202 and there is no Retry-After header: read status, http_status and retry_after_seconds from the JSON body. Errors before an engine runs (validation, authentication, balance, rate limits) use the error envelope below.
  • With output_format text or markdown, a completed request returns 200. So does a refunded failure: with text output the body is empty and there is no status header, so an empty body may be a failure rather than a blank page; with markdown output the body is still the usual wrapper, so check its Status line. Use JSON output when you need to tell them apart. A timeout still returns 503 with a JSON body.
  • An async submit returns 202 with status: "processing" and a poll_url.
  • A replay (same Idempotency-Key with the same request) returns the stored OUTCOME (the status field) with that outcome's normal HTTP code, which is not always the code first seen: a slow first response may have arrived as an early-flushed 202 carrying http_status, and its replay is then 200 for a success. The normal codes are: a success 200, a refunded request 202 with status: "refunded", and a timeout 503 with status: "timeout", a Retry-After header and retry_after_seconds in the body. Replaying an in-flight async request returns 202 JSON with the poll_url. This is about POST replays. GET /v1/ocr/{request_id} is separate: it returns 200 for a finished request only while OCR history is retained, and 410 result_not_retained otherwise; refunded and timeout outcomes read as failed there.

Plain-text conversion rules

output_format: "text" converts the engine output like this. With the default JSON format, extracted_text stays the raw engine output and extracted_text_plain carries this conversion when it differs.

  • Tables: markdown tables (pipe rows with a separator row of 3 or more dashes) become tab-separated rows. Separator rows are dropped and <br> inside a cell becomes a space. Pipe lines without a separator row are left as they are.
  • Code fences: the fence lines are dropped and the content is kept verbatim.
  • Headings: the # to ###### markers are removed, and closing #s only when preceded by whitespace (# C# becomes C#).
  • Horizontal rules: a line whose content (ignoring surrounding spaces) is exactly --- is kept, because PDF pages are joined with a blank line, ---, and a blank line, so it marks page breaks (use pages and pages_total for the authoritative page count). ***, ___, - - -, * * * and _ _ _ are dropped.
  • Bullets: lines starting with "* " become "- ".
  • Emphasis: ***, **, * and ~~ are stripped using flanking rules, so 5 * 3 and 2*3*4 survive. Underscores are not treated as emphasis.
  • Inline code: the backtick delimiters (matched by equal run length) are removed and the content is kept literal, so emphasis and images inside code are not touched.
  • Images: ![alt](url) is removed entirely.
  • Escapes: \*, \_, \|, \# and \` become the literal character.
  • Everything else is unchanged: links [text](url), underscores and bare URLs stay as they are. Text that is already plain is returned byte-identical.

GET /v1/ocr/{request_id} — Poll for a result

An async request (mode: "async") returns status: "processing" and a request_id. Poll this endpoint with that ID until status is no longer queued or processing. GET returns these statuses: queued and processing (still running), then succeeded, partial (some text recovered), failed or rejected. GET never returns refunded or timeout: the router stores those outcomes as failed (read provider_error). Those two words appear only in the original POST response. For a partial result the full text is not stored: read extracted_text_preview (up to 2,000 characters) and warning. Or set webhook_url to be called instead. The same endpoint recovers the saved result of a synchronous request whose connection dropped. Polling only reads the saved request: it does not run OCR again and is not charged. It takes no Idempotency-Key.

bash
curl https://api.open-ocr.com/v1/ocr/req_abc123 \
  -H "Authorization: Bearer sk-ocr-your-api-key"

# Still running: read the "status" field, not the HTTP code
# { "request_id": "req_abc123", "status": "processing" }

# Partial (some text recovered): extracted_text is null; only the preview is stored
# { "request_id": "req_abc123", "status": "partial", "extracted_text": null,
#   "extracted_text_preview": "First 2,000 characters...", "warning": "..." }

# Completed: 200 OK (a replay of a finished request)
# {
#   "request_id": "req_abc123",
#   "status": "succeeded",
#   "engine": "mistral-mistral-ocr-4-1",
#   "extracted_text": "Invoice #1042...",
#   "pages": 1,
#   "cost_debited": 0.004
# }

Poll every few seconds and stop on a terminal status. If OCR history is turned off for your account the saved text is not retained; see recovering results. The charge for a request is the cost_debited value in the original POST response (and cost_usd in the webhook). This GET repeats it only while OCR history is enabled: with history off it returns 410 result_not_retained.

Error Codes

All errors return a consistent JSON envelope:

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

The machine-readable field is error.code(not type). Errors do not always include a request_id.

400invalid_request

Missing or malformed request body, missing Idempotency-Key, a Content-Type other than application/json, or an engine that exists but is switched off (message "engine is not available").

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

The engine ID is not in the catalog. The suggestions array lists close matches; see GET /v1/engines for every valid ID. An engine that exists but is disabled returns 400 invalid_request "engine is not available" instead.

json
{ "error": { "code": "unknown_engine", "message": "'mistral-ocr-4-1' is not a known engine id. Did you mean: mistral-mistral-ocr-4-1?", "suggestions": ["mistral-mistral-ocr-4-1"] } }
401authentication_error

Missing or invalid API key. Check your Authorization header.

json
{ "error": { "code": "authentication_error", "message": "Invalid API key" } }
402insufficient_balance

Account balance too low. Add credits at open-ocr.com/pricing.

json
{ "error": { "code": "insufficient_balance", "message": "Insufficient balance to process any pages. Need $0.004, have $0.0001" } }
403insufficient_scope

A read-only API key was used for POST /v1/ocr, the batch endpoint or engine warm-up. Use a full-access key.

json
{ "error": { "code": "insufficient_scope", "message": "This API key is read-only and cannot perform OCR requests. Use a full-access key." } }
413payload_too_large

Request 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.

json
{ "error": { "code": "payload_too_large", "message": "Request body too large. Maximum size is 10 MB." } }
429rate_limited

More than 300 requests in 60 seconds on this API key. Wait for the Retry-After header; the body has no retry_after_seconds.

json
{ "error": { "code": "rate_limited", "message": "Rate limit exceeded. Retry after 18s" } }
429engine_rate_limited

The engine you chose is at its own request or concurrency limit and its wait queue could not seat this request. Not charged. Retry after the Retry-After header or retry_after_seconds.

json
{ "error": { "code": "engine_rate_limited", "message": "Engine mistral-mistral-ocr-4-1 is at its rate limit (60 req/min) and the wait queue could not seat this request (queue_full). Retry after 12s. Request id req_abc123." }, "retry_after_seconds": 12 }
429api_key_limit_reached

This 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.

json
{ "error": { "code": "api_key_limit_reached", "message": "This API key has reached its 10000 requests/month limit (current UTC month usage: 10000). Use another key or wait until the next UTC month. No credits were charged." } }
500internal_error

Server-side error. A failure on our side is never charged — retry safely with the same Idempotency-Key.

json
{ "error": { "code": "internal_error", "message": "Failed to process OCR request" } }
503engine_unavailable

The engine is not configured on this server. The request never reached an engine, so it is not charged. Try another engine. A coming-soon engine returns this code with HTTP 400.

json
{ "error": { "code": "engine_unavailable", "message": "This engine isn't configured on this server" } }

For retry strategies per error code, see the Error Codes page.

Billing on Failed Requests

A failure is not automatically free. What you pay depends on whether the engine actually ran.

  • The engine never ran — invalid input, authentication, rate limits, an unavailable or misconfigured engine, or any failure on our side. You are not charged, and any provisional debit is refunded.
  • The engine ran and then failed — it errored partway, timed out mid-generation, or returned unusable output. You are charged the provider's cost for that attempt, passed through at cost including provider fees. The initial estimate is not a billing cap. Every customer-authorized retry is billable.
  • We charge only evidenced costs. If no provider cost is evidenced when the failure is settled, there is no charge and the provisional debit is refunded. The charge is the cost_debited value in the original POST response (and cost_usd in the webhook); GET /v1/ocr/{request_id} repeats it only when OCR history is enabled.

On the wire this means cost_debited may be non-zero on a POST response whose status is "refunded" (HTTP 202) or "timeout" (HTTP 503, or 202 if the headers were already sent); GET /v1/ocr/{request_id} reports the same request as "failed". The word "refunded" stays even when only part of the hold came back. A charged failure does not get a status or error code of its own — cost_debited is where you read the charge, warning states it in words, and provider_error tells you what went wrong. Successful requests are unaffected and bill at the published price.

json
{
  "request_id": "req_abc123",
  "status": "refunded",
  "engine": "google-gemini-3.1-flash-lite",
  "extracted_text": null,
  "cost_debited": 0.0004,
  "provider_error": "Google returned no text for this image. Re-sending it to this engine usually gives the same result; try a different engine.",
  "warning": "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"
}

Here the engine was quoted at $0.0006 for the page and the provider billed us $0.0004 for the tokens of the attempt that returned no text, so $0.0004 is what you pay.

Full policy, including a worked example, on the Error Codes page.

Rate Limits

POST /v1/ocr, POST /v1/ocr/batch, GET /v1/usage and engine warm-up share a limit of 300 requests per sliding 60 seconds per API key (a batch counts once). Polling a result and the public catalog endpoints are not limited. Separately, each engine has its own limit; a request it cannot seat gets 429 engine_rate_limited.

bash
# Headers on POST /v1/ocr and GET /v1/usage responses:
X-RateLimit-Limit: 300         # requests allowed per 60s window
X-RateLimit-Remaining: 242     # requests left
X-RateLimit-Reset: 60          # always 60 on an allowed request; on a 429, seconds until a slot frees

# On 429:
Retry-After: 18                # seconds to wait
python
import time, uuid, requests

def ocr_with_retry(payload, api_key, max_retries=3):
    idempotency_key = str(uuid.uuid4())  # one key per logical request, reused on every retry
    # 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 != 429:
            return resp
        wait = float(resp.headers.get("Retry-After", 2 ** attempt))
        time.sleep(wait)
    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)

# 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"])

API Key Guide

Creating a key: Navigate to Dashboard → API Keys and click Create Key. Give it a descriptive label so you can identify it later.

Storing your key: Copy the key immediately — it's only shown once. Store it in a secret manager (AWS Secrets Manager, HashiCorp Vault, etc.) or as an environment variable. Never commit it to source control.

Rotating a key: Create a new key, update your services to use it, then revoke the old key from the dashboard. Zero-downtime rotation: both keys are valid until the old one is revoked.

Key scopes: A key is Full Access or Read Only, chosen when you create it. A read-only key can poll results and read usage; POST /v1/ocr, the batch endpoint and engine warm-up refuse it with 403 insufficient_scope.

bash
# Store your API key as an environment variable
export OPENOCR_API_KEY="sk-ocr-your-api-key"

# Reference it in curl
curl -X POST https://api.open-ocr.com/v1/ocr \
  -H "Authorization: Bearer $OPENOCR_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{"engine":"mistral-mistral-ocr-4-1","input":{"type":"url","url":"https://example.com/doc.png"}}'
python
import os
import uuid

import requests

response = requests.post(
    "https://api.open-ocr.com/v1/ocr",
    headers={
        "Authorization": f"Bearer {os.environ['OPENOCR_API_KEY']}",
        "Idempotency-Key": str(uuid.uuid4()),
    },
    json={
        "engine": "mistral-mistral-ocr-4-1",
        "input": {"type": "url", "url": "https://example.com/doc.png"},
    },
)
response.raise_for_status()
body = response.json()
assert body["status"] == "succeeded", body
print(body["extracted_text"])
typescript
// Node.js 18+: load the key from the environment
const response = await fetch("https://api.open-ocr.com/v1/ocr", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.OPENOCR_API_KEY}`,
    "Content-Type": "application/json",
    "Idempotency-Key": crypto.randomUUID(),
  },
  body: JSON.stringify({
    engine: "mistral-mistral-ocr-4-1",
    input: { type: "url", url: "https://example.com/doc.png" },
  }),
});
const result = await response.json();
if (result.status !== "succeeded") throw new Error("OCR ended as " + (result.status ?? result.error?.code)); // error envelopes have no status
if (!response.ok) throw new Error(result.error?.message ?? `HTTP ${response.status}`);
console.log(result.extracted_text);

Official OpenOCR SDKs are coming soon; these examples call the REST API directly.

GET /v1/engines

List all OCR engines with their status. No request body or authentication required. Field reference: All endpoints.

bash
curl https://api.open-ocr.com/v1/engines \
  -H "Authorization: Bearer $OPENOCR_API_KEY"

# 200 OK — a list object; the engines are in data
# {
#   "object": "list",
#   "data": [
#     {
#       "id": "mistral-mistral-ocr-4-1",
#       "name": "Mistral OCR 4.1",
#       "provider": "mistral",
#       "price_per_page_usd": 0.004,
#       "status": "available",
#       "accepts": ["image", "pdf"],
#       "max_pages_per_request": 1000,
#       "native_pdf": true
#     },
#     ...
#   ]
# }

File Upload Constraints

ConstraintLimitNotes
Max request body10 MBApplies to base64 payloads. Use URL input for larger files.
Supported image formatsPNG, JPEG, WEBP, GIF, TIFF, BMPTIFF/BMP require single-page engines.
PDF supportYes (multi-page)Requires an engine with pdf capability. See /v1/engines.
Max pages (PDF)Engine-dependentmax_pages_per_request in GET /v1/engines. On 2026-11-18: language-model engines 1 page, local-tesseract 500, Mistral OCR 4.1 1,000.
URL inputPublicly accessible URLSupports http:// and https://. No auth-gated URLs.
Base64 inputRaw base64 string, no data: prefixStrip data:image/png;base64, before sending.
bash
# Upload a local file via base64
IMG_B64=$(base64 -w 0 /path/to/invoice.png)

curl -X POST https://api.open-ocr.com/v1/ocr \
  -H "Authorization: Bearer $OPENOCR_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d "{
    \"engine\": \"mistral-mistral-ocr-4-1\",
    \"input\": {
      \"type\": \"base64\",
      \"data_base64\": \"$IMG_B64\",
      \"mime_type\": \"image/png\"
    }
  }"
python
import base64, requests, os, uuid

with open("invoice.png", "rb") as f:
    b64 = base64.b64encode(f.read()).decode()

resp = requests.post(
    "https://api.open-ocr.com/v1/ocr",
    headers={
        "Authorization": f"Bearer {os.environ['OPENOCR_API_KEY']}",
        "Idempotency-Key": str(uuid.uuid4()),
    },
    json={
        "engine": "mistral-mistral-ocr-4-1",
        "input": {"type": "base64", "data_base64": b64, "mime_type": "image/png"},
    },
    timeout=60,
)
resp.raise_for_status()  # an error envelope has no "status" field
body = resp.json()
assert body["status"] == "succeeded", body
print(body["extracted_text"])