Skip to content

Tasks API

/v1/tasks is the shared asynchronous parsing API for API Server, Router, and compatible SaaS: submit a JSON manifest, upload missing files, poll, and download results per file. Existing clients should read the 4.1 migration guide. For synchronous single-file requests, see the file-parse API.

First HTTP request · Request fields · Response fields · Successful responses · Errors · Downloads

Startup and authentication

mineru-kit api-server --host 127.0.0.1 --port 8000 --tier auto

The service exposes deployment-specific definitions at /docs and /openapi.json. When an API key is configured, send Authorization: Bearer <API_KEY> on API requests. Local services without a key do not require that header. The API base may include a reverse-proxy path prefix.

Routes

Method and path Success response Purpose
POST /v1/tasks 202, CreateTaskResponse Submit a JSON manifest.
PUT files[].upload.url Local/Router: 200, UploadFileResponse Upload one file's raw bytes; accept successful 2xx responses from object storage.
GET /v1/tasks/{task_id} 200, TaskDetailResponse Read a complete status snapshot.
POST /v1/tasks/{task_id}/cancel 200, CancelTaskResponse Cancel unfinished files; no request body required.

Local upload paths are /v1/tasks/{task_id}/uploads/{file_id}; clients should use the returned full URL. There are no task/file lists, public DELETE operations, or batch-result endpoint. The main API Server and Router do not expose /v1/file_parse.

Creation request

POST /v1/tasks accepts only application/json. Put all business parameters in the JSON body. Query parameters, unknown fields, and invalid values return 400; other content types return 415.

Field Type Default or requirement
files object[] Required, 1–100 entries; not a JSON-encoded string.
tier string or null Optional; flash/basic/standard/advanced, as described below.
ocr_mode string auto; accepts auto/txt/ocr.
page_range string Empty means the whole document; PDF ranges include 1-5, r1, and all.
output_formats string[] ["default"]; nonempty, values from default/docx/html/latex, deduplicated in first-occurrence order.

Each files[] entry:

Field Type Requirement
file_name string Required logical basename, 1–1024 characters, retaining its extension without directory components. Duplicate names are allowed.
bytes integer or null Required positive integer for uploads. Optional for URLs; when supplied, must match the actual size.
url string or null HTTP(S) download URL; omitted or null means a client upload.
sha256sum string or null Optional 64-character lowercase hexadecimal SHA-256 for validation and, for uploads, cache preflight.
page_range string or null Optional per-file PDF range overriding the global range. Non-PDF native documents still parse as a whole.

Requests must omit file_id/client_file_id, including null values. The server allocates public file_id values in input order; duplicate names or content still receive different IDs. Use IDs to correlate uploads, queries, cancellation, and downloads. Local/Router result Files IDs match these IDs; Files lookup returns 404 before the result exists. Source-cache IDs remain private.

For both uploads and URL inputs, file_name must not contain /, backslashes, colons, or Unicode Cc control characters, and must not be exactly . or ... Unicode names, spaces, .report.csv, and report..csv are allowed. Accepted names are preserved without trimming, percent-decoding, or silently stripping directory components.

Names such as ../report.csv, C:\input\report.csv, and report.csv:stream return 400 invalid_request with error.param="files.<index>.file_name". One invalid name rejects the entire manifest before allocating tasks, file IDs, or upload links; Routers do not forward it downstream.

This tightens acceptance of path-like names: custom clients must extract the basename locally before submission. The official SDK already sends path.name. Logical names identify formats and display names, not server filesystem locations; storage continues to use generated identifiers or content hashes. Local CLI paths still support ../ and absolute paths. The multipart file-parse API retains its compatibility behavior of stripping directory components before validating the resulting basename.

Tier selection

  • For PDFs/images, an omitted or null tier selects the first supported value in standard → basic → flash → advanced order. Advanced is selected automatically only when it is the sole available tier.
  • An explicitly unsupported PDF/image tier rejects the entire creation request with 400 invalid_request, error.param="tier". No work is accepted and no tier substitution occurs.
  • Every normally available compatible service supports existing native document formats. Office, HTML, and other native documents always use Flash, regardless of /v1/tiers or a valid requested tier. Empty strings and unknown enum values are still invalid.
  • Mixed batches select tiers per file. On a Standard-capable service, a PDF + DOCX request without a tier uses Standard and Flash respectively. Selection is fixed at admission, not repeated during queuing or forwarding. Successful files report the actual value in parse.tier.

Example request and creation receipt

Sizes, IDs, URLs, and timestamps below are illustrative; use the actual byte count for a real upload.

{
  "files": [{"file_name": "report.pdf", "bytes": 12345}],
  "tier": "standard",
  "ocr_mode": "auto",
  "output_formats": ["default", "docx"]
}

See the 202 creation receipt for the matching response.

URL inputs use the same creation endpoint, for example:

{
  "files": [{"file_name": "report.pdf", "url": "https://example.com/report.pdf"}],
  "output_formats": ["html"]
}

The server downloads URL inputs without a client PUT; replace the example with a real download URL allowed by the deployment.

Response fields

Success responses are direct objects without a data/task envelope. Below, ? marks an optional field and is not part of its name.

Response Top-level fields files[] fields
CreateTaskResponse task_id, status, files file_id, file_name, status, upload?
TaskDetailResponse task_id, status, created_at, started_at?, finished_at?, output_formats, progress, files, error? file_id, file_name, status, bytes?, url?, upload?, parse?, result_url?, error?
CancelTaskResponse task_id, status (always canceled), finished_at, files file_id, file_name, status, parse?, result_url?, error?
UploadFileResponse task_id, file_id, status (the uploaded file's state) None

task_id/file_id/file_name/status are strings, files is an array, bytes is an integer, url/result_url are strings, and output_formats is a string array. Time fields are ISO-8601 UTC strings.

Shared response objects

Nested object Fields and meaning
upload url: string, headers: object (string pairs, possibly empty), expires_at: integer (Unix seconds). Present only when an upload is currently needed.
parse tier: string, duration_ms?: integer, parser_version?: string. Successful files only; version identifies the executing worker. Duration includes source reading/downloading, validation, parsing, and export, excluding waits for upload, preparation slots, or parsing queues.
progress Required integers completed/failed/total. Canceled files count as neither completed nor failed; total is the number of inputs.
error Required nonempty code: string, message: string, and param?: string. May appear at the GET top level, in GET files, or in failed files of cancellation receipts; no type field.

Tasks success responses recursively omit nulls, preserving 0/false/[]/{}. Each response is a complete snapshot: an absent field has no current value, so do not retain stale upload links. Clients should tolerate future extra fields. Public HTTP errors also omit absent param values; Files and file-parse use separate null rules.

Successful response examples

POST creation receipt (202)

{
  "task_id": "job_example",
  "status": "waiting-file",
  "files": [{
    "file_id": "file-example",
    "file_name": "report.pdf",
    "status": "waiting-file",
    "upload": {
      "url": "http://127.0.0.1:8000/v1/tasks/job_example/uploads/file-example",
      "headers": {},
      "expires_at": 1800003600
    }
  }]
}

202 means accepted. Creation receipts omit input sizes, parsing statistics, and result URLs; use GET for details even if a file has already completed.

GET task detail (200)

{
  "task_id": "job_example",
  "status": "completed",
  "created_at": "2026-10-28T00:00:00Z",
  "started_at": "2026-10-28T00:00:02Z",
  "finished_at": "2026-10-28T00:00:10Z",
  "output_formats": ["default", "docx"],
  "progress": {"completed": 1, "failed": 0, "total": 1},
  "files": [{
    "file_id": "file-example",
    "file_name": "report.pdf",
    "status": "completed",
    "bytes": 12345,
    "parse": {"tier": "standard", "duration_ms": 8000, "parser_version": "4.1.0"},
    "result_url": "http://127.0.0.1:8000/v1/files/file-example/content"
  }]
}

POST cancellation receipt (200)

{
  "task_id": "job_example",
  "status": "canceled",
  "finished_at": "2026-10-28T00:00:05Z",
  "files": [{"file_id": "file-example", "file_name": "report.pdf", "status": "canceled"}]
}

PUT upload confirmation (200)

Example local PUT receipt: {"task_id":"job_example","file_id":"file-example","status":"pending"}. Successful object-storage PUT responses need not contain this JSON; query Tasks afterwards to confirm readiness.

Errors

Request-level errors use a non-2xx status and {"error": ...}, for example:

{
  "error": {
    "code": "task_already_terminal",
    "message": "Task is canceled"
  }
}
HTTP Common code Scenario
400 invalid_request, page_range_invalid Invalid fields, tiers, ranges, or old parameters.
400 upload_size_mismatch, file_hash_mismatch, upload_interrupted Upload validation or transfer failure.
401 invalid_api_key Invalid credentials on an authenticated service.
404 task_not_found, upload_not_found Task unavailable/collected, or no such upload file ID.
409 task_already_terminal, file_already_terminal Canceling a terminal task or uploading to a file no longer accepting bytes.
410 upload_expired Upload window expired.
415 invalid_request Creation request is not JSON.
503 quality_tier_unavailable, server_shutting_down, or model preload codes The service cannot accept the request.

Asynchronous download, parsing, and export failures usually appear in files[].error inside a 200 query snapshot; HTTP 200 does not mean parsing succeeded. Public errors contain required nonempty code, message, and optional param; type is neither emitted nor accepted. Absent param values are omitted, although receivers also accept null. Branch on HTTP status and code rather than parsing message text. Inspect every file's state: an absent top-level error does not establish that all files succeeded.

Uploads, URLs, and caching

PUT raw bytes using the returned upload.url/headers; no completion call is required. Upload only when a file is waiting-file and has an upload object. Otherwise poll. Each validated file queues independently without waiting for other files; waiting uploads do not reserve parsing capacity.

  • Valid hash-based cache hits skip uploads. Only source bytes are reused; each task parses with its own parameters. Concurrent first uploads may transfer duplicate bytes, but source storage is deduplicated.
  • URL inputs are downloaded by the server without an upload action, HEAD requirement, or Content-Length requirement. file_name determines the format; actual bytes are populated after download and supplied sizes/hashes are checked. URLs are downloaded each time, without hash-based download skipping.
  • Local URL sources default to HTTPS only. HTTP requires --allow-http-source; defaults are a 60-second download timeout and a 200 MiB size limit. Direct client uploads have no fixed size or PDF page limit, though deployments may impose gateway limits.
  • URL sources must resolve exclusively to public unicast addresses. Workers validate all IPv4/IPv6 results and connect to a validated IP. Private, loopback, link-local, cloud metadata, and special addresses fail the file with unsupported_source. Downloads use direct connections and reject redirects. HTTP_PROXY, HTTPS_PROXY, and ALL_PROXY are ignored for URL source downloads. TLS verification honors SSL_CERT_FILE / SSL_CERT_DIR. Clients can upload documents from internal storage. Externally accessible deployments should configure --api-key and restrict worker egress.
  • When using a Fake-IP proxy, configure worker DNS to return actual public addresses. Reserved ranges such as 198.18.0.0/15 are rejected.
  • Upload links expire 3600 seconds after creation and are not renewed by polling. Uploads admitted before the deadline may finish; files not yet admitted become failed/upload_expired. Processing of successfully uploaded files is not limited by this deadline.
  • Do not repeat successful PUTs. Query after a lost response: skip upload for pending/running/completed, poll waiting-file without an upload object, and retry within bounds only after failure when a valid upload action remains. Expired uploads need a new task. Chunk-level resumable uploads are not supported.

Local source caches default to 24-hour retention with collection every five minutes; active tasks and transfers protect source bytes. API/Router task records and indexes are in memory and are not guaranteed to survive restarts.

States and cancellation

File state Meaning
waiting-file Waiting for/receiving uploads, URL downloads, validation, or object-storage confirmation.
pending Input ready, waiting for parsing resources.
running Parsing, exporting, or saving results.
completed All requested formats succeeded; the result is downloadable.
failed Input, parsing, or export failed; inspect error.
canceled An unfinished file was canceled.

Parent aggregation prioritizes running, then pending, then waiting-file. All successful files yield completed; terminal success/failure mixtures yield partial; no successes yield failed. Cancellation sets the parent to canceled. A parent may move from running back to waiting-file while completed files remain downloadable.

Cancellation preserves completed/failed files and marks the others canceled. Receipt file states are therefore limited to completed/failed/canceled. Non-interruptible computation or cleanup may still finish internally, but late results cannot overwrite published cancellation states. Canceling an already terminal task returns 409 task_already_terminal.

See the cancellation receipt for a single-file task that was still processing.

Outputs and downloads

output_formats Result per input
["default"] ZIP with markdown.md, middle_json.json, structured_content.json, and images/.
["docx"] A DOCX with embedded images.
["html"] An HTML file with embedded images; formula scripts retain renderer behavior.
["latex"] ZIP with document.tex and images/.
Multiple formats One flat ZIP, without nested ZIPs; DOCX/HTML names are document.docx/document.html.

Each input is parsed once. One files[].result_url is published after all requested formats succeed. If any format fails, that file becomes failed/result_packaging_failed without partial artifacts; other files continue. There is no combined batch ZIP or top-level result_url. Completed files can be downloaded before the parent finishes.

ModelJson is internal. include_model_output is removed and returns 400 even when false; results do not contain model_output.json.

Local services and Router return Files URLs; SaaS may return signed object-storage URLs. Use returned result URLs without constructing storage paths. Attach the API key only to same-origin API requests, reevaluating every redirect; never forward it to object storage. During result retention, query again to renew an expired download signature. Polling and downloads do not render again, and unfinished files do not cause completed results to be collected early.

Runnable client examples

Run these Bash examples from the repository root. The standard-library Python client calculates real sizes and hashes, uploads files, and downloads per-file results:

MINERU_API_URL=http://127.0.0.1:8000 \
  bash scripts/http_task_example.sh report.pdf notes.docx

OUTPUT_FORMATS=default,docx RESULT_DIR=results \
MINERU_API_URL=http://127.0.0.1:8000 \
  bash scripts/http_task_example.sh report.pdf

# Resume with the original file list and order, without creating again.
TASK_ID=job_example MINERU_API_URL=http://127.0.0.1:8000 \
  bash scripts/http_task_example.sh report.pdf

Set MINERU_API_KEY for authentication, MINERU_TIER/OCR_MODE/PAGE_RANGE for parsing options, and SEND_HASH=0 to disable hash preflight. MAX_POLLS/POLL_INTERVAL default to 300/1 and bound polling; CONNECT_TIMEOUT/REQUEST_TIMEOUT bound individual transfers. Creation is not automatically retried. Exit codes: 0 all successful, 2 partial success, 1 failure/cancellation, 124 polling exhausted. Completed downloads remain on disk.

For direct HTTP calls, append /v1/tasks/{URL-encoded task_id} to the configured API base for queries, and append /cancel to that route for POST cancellation. Save creation IDs for recovery; Tasks does not return a status_url.

Dynamic Router upstreams and cascading

For runtime registration, graceful removal, and multi-level deployments, see deploy and manage a Router.