Skip to content

Deprecated interfaces

This page lists the interfaces of the Doc2X Open Platform API that are deprecated. A deprecated interface can still be called, but it is no longer recommended, receives no new features and no higher limits, and may be discontinued later. Once a date is set it will be announced on this page first; until then existing calls are not affected.

New integrations should use the replacement; existing ones should migrate as described here.

Overview

Deprecated interfacePurposeStatusReplacement
POST /api/v2/parse/pdfPDF parsing with the file uploaded directly in the request bodyStill callable; no discontinuation date yetPOST /api/v2/parse/preupload (preupload)

Interfaces that are not listed here are not affected, including status (GET /api/v2/parse/status), export (POST /api/v2/convert/parse, GET /api/v2/convert/parse/result) and the image interfaces. The image interfaces still take the image in the request body and are not being deprecated.

POST /api/v2/parse/pdf direct PDF upload

This interface submits a PDF for parsing with its binary content in the request body. Its replacement is preupload: get a task uid and an upload URL first, then send the file to that URL. Both ways feed the same parsing service; once you have the uid, status queries, export and billing are the same.

Differences from preupload

ItemDirect upload (deprecated)Preupload
How to submitOne request with the file in the bodyCall POST /api/v2/parse/preupload, then PUT the file to the returned upload URL
File sizeUp to 300 MiBUp to 1 GiB
Pages per fileUp to 1000Up to 2000
Upload timeThe whole file must arrive within 60 secondsThe upload URL expires 10 minutes after it is issued; upload right away
A problem with the fileReported by an error code on submissionNot checked on submission; the error code is returned by the status query
Status, export, billingSameSame

Besides size and pages, both ways check the account's concurrency limits (tasks in progress, pages in progress) and its balance. The pages of a document count against the pages-in-progress limit: a large document close to that limit is only accepted once the account's other tasks have finished.

Migrating to preupload

  1. Replace POST /api/v2/parse/pdf with POST /api/v2/parse/preupload. The request needs no body and returns the task uid and an upload url.
  2. PUT the binary content of the file to url. Do not send Authorization with it and do not use multipart/form-data.
  3. The rest is unchanged: poll GET /api/v2/parse/status with the uid, then read the result or export as before.
  4. Adjust error handling: direct upload checks everything on submission, preupload checks in two stages. The preupload request itself only checks the task limit and that the balance covers one page, and returns parse_concurrency_limit or parse_quota_limit otherwise. The file itself, its pages, and the concurrency limit and balance for the actual number of pages are checked after the upload; those errors are returned by the status query (a code other than success). The code for an invalid file differs too: parse_pdf_invalid for direct upload, parse_file_invalid for preupload.

What changes in the requests:

bash
# Before: one request with the file in the body
curl --request POST 'https://v2.doc2x.noedgeai.com/api/v2/parse/pdf' \
  --header "Authorization: Bearer $DOC2X_API_KEY" \
  --data-binary '@paper.pdf'

# Now: get the uid and the upload URL, then upload the file
curl --request POST 'https://v2.doc2x.noedgeai.com/api/v2/parse/preupload' \
  --header "Authorization: Bearer $DOC2X_API_KEY"
curl --request PUT "$UPLOAD_URL" --data-binary '@paper.pdf'

The preupload response has a url in addition to the uid (the ID and the address below are placeholders and cannot be called):

json
{"code":"success","data":{"uid":"TASK_UID","url":"https://upload.example.invalid/signed.pdf"}}

Examples after migration

The four programs below do the same thing: submit paper.pdf through preupload, poll until parsing has finished, and print the number of pages. The API Key is read from the environment variable DOC2X_API_KEY; do not put it in code or commit it.

python
import os
import time

import requests

BASE = "https://v2.doc2x.noedgeai.com"
AUTH = {"Authorization": "Bearer " + os.environ["DOC2X_API_KEY"]}


def call(method, path, **kwargs):
    """Sends a request and reads the response as JSON; a network error, or a body that is not JSON, counts as {"code": "network"}."""
    try:
        return requests.request(method, BASE + path, headers=AUTH, **kwargs).json()
    except (requests.RequestException, ValueError):
        return {"code": "network"}


def parse_pdf(path, give_up_after=1800):
    """Parses a PDF through preupload and returns the result. Raises on failure."""
    # Step 1 (this used to be a POST of the file to /api/v2/parse/pdf): get the task uid and an upload URL; no request body
    body = call("POST", "/api/v2/parse/preupload", timeout=30)
    if body.get("code") != "success":
        raise RuntimeError(f"{body.get('code')}: {body.get('msg')}")
    uid, url = body["data"]["uid"], body["data"]["url"]

    # Step 2: PUT the file as it is to the upload URL. The URL expires, so upload right away; do not send Authorization
    with open(path, "rb") as f:
        requests.put(url, data=f, timeout=600).raise_for_status()

    # Step 3 (unchanged): poll the status with the uid. Errors such as too many pages or an invalid file are now returned here
    deadline = time.time() + give_up_after
    while time.time() < deadline:
        time.sleep(3)
        body = call("GET", "/api/v2/parse/status", timeout=30, params={"uid": uid})
        if body.get("code") in ("network", "internal_error"):
            continue  # transient: keep polling
        if body.get("code") != "success":
            raise RuntimeError(f"Parsing failed: {body.get('code')} {body.get('msg')}")
        if body["data"]["status"] == "success":
            return body["data"]["result"]
    raise TimeoutError(f"uid {uid} has no result yet")


if __name__ == "__main__":
    result = parse_pdf("paper.pdf")
    print("Pages:", len(result["pages"]))
javascript
// Node.js 18 or later, no dependencies. Save as a .mjs file and run it
import { readFile } from "node:fs/promises";
import { setTimeout as sleep } from "node:timers/promises";

const BASE = "https://v2.doc2x.noedgeai.com";
const AUTH = { Authorization: `Bearer ${process.env.DOC2X_API_KEY}` };

// Sends a request and reads the response as JSON; a network error, or a body that is not JSON, counts as { code: "network" }
async function call(path, { timeout, ...options }) {
  try {
    const response = await fetch(BASE + path, { ...options, headers: AUTH, signal: AbortSignal.timeout(timeout) });
    return await response.json();
  } catch {
    return { code: "network" };
  }
}

/** Parses a PDF through preupload and returns the result. Throws on failure. */
async function parsePdf(path, giveUpAfter = 1_800_000) {
  // Step 1 (this used to be a POST of the file to /api/v2/parse/pdf): get the task uid and an upload URL; no request body
  let body = await call("/api/v2/parse/preupload", { method: "POST", timeout: 30_000 });
  if (body.code !== "success") throw new Error(`${body.code}: ${body.msg}`);
  const { uid, url } = body.data;

  // Step 2: PUT the file as it is to the upload URL. The URL expires, so upload right away; do not send Authorization
  const upload = await fetch(url, { method: "PUT", body: await readFile(path), signal: AbortSignal.timeout(600_000) });
  if (!upload.ok) throw new Error(`Upload failed: HTTP ${upload.status}`);

  // Step 3 (unchanged): poll the status with the uid. Errors such as too many pages or an invalid file are now returned here
  const deadline = Date.now() + giveUpAfter;
  while (Date.now() < deadline) {
    await sleep(3000);
    body = await call(`/api/v2/parse/status?uid=${uid}`, { timeout: 30_000 });
    if (body.code === "network" || body.code === "internal_error") continue; // transient: keep polling
    if (body.code !== "success") throw new Error(`Parsing failed: ${body.code} ${body.msg}`);
    if (body.data.status === "success") return body.data.result;
  }
  throw new Error(`uid ${uid} has no result yet`);
}

const result = await parsePdf("paper.pdf");
console.log("Pages:", result.pages.length);
java
// Java 11 or later. Dependency: com.google.code.gson:gson
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;
import java.time.Duration;

public class PdfPreupload {
    static final String BASE = "https://v2.doc2x.noedgeai.com";
    static final String KEY = System.getenv("DOC2X_API_KEY");
    static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();

    /** Sends a request and reads the response as JSON; a network error, or a body that is not JSON, counts as {"code": "network"}. */
    static JsonObject call(HttpRequest.Builder request, int timeoutSeconds) throws InterruptedException {
        try {
            HttpRequest built = request.header("Authorization", "Bearer " + KEY)
                    .timeout(Duration.ofSeconds(timeoutSeconds)).build();
            String text = HTTP.send(built, HttpResponse.BodyHandlers.ofString()).body();
            return JsonParser.parseString(text).getAsJsonObject();
        } catch (IOException | RuntimeException e) {
            JsonObject network = new JsonObject();
            network.addProperty("code", "network");
            return network;
        }
    }

    static String text(JsonObject object, String name) {
        return object.has(name) && object.get(name).isJsonPrimitive() ? object.get(name).getAsString() : "";
    }

    /** Parses a PDF through preupload and returns the result. Throws on failure. */
    static JsonObject parsePdf(Path path, long giveUpAfterSeconds) throws IOException, InterruptedException {
        // Step 1 (this used to be a POST of the file to /api/v2/parse/pdf): get the task uid and an upload URL; no request body
        JsonObject body = call(HttpRequest.newBuilder(URI.create(BASE + "/api/v2/parse/preupload"))
                .POST(HttpRequest.BodyPublishers.noBody()), 30);
        if (!text(body, "code").equals("success")) {
            throw new IOException(text(body, "code") + ": " + text(body, "msg"));
        }
        String uid = text(body.getAsJsonObject("data"), "uid");
        String url = text(body.getAsJsonObject("data"), "url");

        // Step 2: PUT the file as it is to the upload URL. The URL expires, so upload right away; do not send Authorization
        HttpRequest upload = HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofMinutes(10))
                .PUT(HttpRequest.BodyPublishers.ofFile(path)).build();
        int uploaded = HTTP.send(upload, HttpResponse.BodyHandlers.discarding()).statusCode();
        if (uploaded != 200) {
            throw new IOException("Upload failed: HTTP " + uploaded);
        }

        // Step 3 (unchanged): poll the status with the uid. Errors such as too many pages or an invalid file are now returned here
        long deadline = System.currentTimeMillis() + giveUpAfterSeconds * 1000;
        while (System.currentTimeMillis() < deadline) {
            Thread.sleep(3000);
            body = call(HttpRequest.newBuilder(URI.create(BASE + "/api/v2/parse/status?uid=" + uid)).GET(), 30);
            String code = text(body, "code");
            if (code.equals("network") || code.equals("internal_error")) {
                continue; // transient: keep polling
            }
            if (!code.equals("success")) {
                throw new IOException("Parsing failed: " + code + " " + text(body, "msg"));
            }
            JsonObject data = body.getAsJsonObject("data");
            if (text(data, "status").equals("success")) {
                return data.getAsJsonObject("result");
            }
        }
        throw new IOException("uid " + uid + " has no result yet");
    }

    public static void main(String[] args) throws Exception {
        JsonObject result = parsePdf(Path.of("paper.pdf"), 1800);
        System.out.println("Pages: " + result.getAsJsonArray("pages").size());
    }
}
go
// Go 1.21 or later, standard library only
package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"time"
)

const base = "https://v2.doc2x.noedgeai.com"

var key = os.Getenv("DOC2X_API_KEY")

type answer struct {
	Code string `json:"code"`
	Msg  string `json:"msg"`
	Data struct {
		UID    string `json:"uid"`
		URL    string `json:"url"`
		Status string `json:"status"`
		Result struct {
			Pages []json.RawMessage `json:"pages"`
		} `json:"result"`
	} `json:"data"`
}

// call sends a request and reads the response as JSON; a network error, or a body that is not JSON, counts as Code = "network"
func call(method, path string, timeout time.Duration) answer {
	request, err := http.NewRequest(method, base+path, nil)
	if err != nil {
		return answer{Code: "network"}
	}
	request.Header.Set("Authorization", "Bearer "+key)
	response, err := (&http.Client{Timeout: timeout}).Do(request)
	if err != nil {
		return answer{Code: "network"}
	}
	defer response.Body.Close()
	var parsed answer
	if json.NewDecoder(response.Body).Decode(&parsed) != nil {
		return answer{Code: "network"}
	}
	return parsed
}

// parsePDF parses a PDF through preupload and returns the number of pages. Returns an error on failure
func parsePDF(path string, giveUpAfter time.Duration) (int, error) {
	// Step 1 (this used to be a POST of the file to /api/v2/parse/pdf): get the task uid and an upload URL; no request body
	body := call(http.MethodPost, "/api/v2/parse/preupload", 30*time.Second)
	if body.Code != "success" {
		return 0, fmt.Errorf("%s: %s", body.Code, body.Msg)
	}
	uid := body.Data.UID

	// Step 2: PUT the file as it is to the upload URL. The URL expires, so upload right away; do not send Authorization
	file, err := os.Open(path)
	if err != nil {
		return 0, err
	}
	defer file.Close()
	info, err := file.Stat()
	if err != nil {
		return 0, err
	}
	upload, err := http.NewRequest(http.MethodPut, body.Data.URL, file)
	if err != nil {
		return 0, err
	}
	upload.ContentLength = info.Size()
	uploaded, err := (&http.Client{Timeout: 10 * time.Minute}).Do(upload)
	if err != nil {
		return 0, err
	}
	uploaded.Body.Close()
	if uploaded.StatusCode != http.StatusOK {
		return 0, fmt.Errorf("Upload failed: HTTP %d", uploaded.StatusCode)
	}

	// Step 3 (unchanged): poll the status with the uid. Errors such as too many pages or an invalid file are now returned here
	deadline := time.Now().Add(giveUpAfter)
	for time.Now().Before(deadline) {
		time.Sleep(3 * time.Second)
		body = call(http.MethodGet, "/api/v2/parse/status?uid="+uid, 30*time.Second)
		switch {
		case body.Code == "network" || body.Code == "internal_error":
			continue // transient: keep polling
		case body.Code != "success":
			return 0, fmt.Errorf("Parsing failed: %s %s", body.Code, body.Msg)
		case body.Data.Status == "success":
			return len(body.Data.Result.Pages), nil
		}
	}
	return 0, fmt.Errorf("uid %s has no result yet", uid)
}

func main() {
	pages, err := parsePDF("paper.pdf", 30*time.Minute)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	fmt.Println("Pages:", pages)
}

Reference

For callers that still use this interface.

ItemDescription
EndpointPOST https://v2.doc2x.noedgeai.com/api/v2/parse/pdf
AuthenticationHeader Authorization: Bearer <API Key>
Request bodyThe binary content of the PDF, not multipart/form-data; no other parameters
LimitsUp to 300 MiB and 1000 pages; the whole body must arrive within 60 seconds

A successful submission returns the task uid, which you then use to query the status:

json
{"code":"success","data":{"uid":"TASK_UID"}}

Error codes

The codes a submission can return. An error response is {"code": "...", "msg": "..."}, with a detail for a few of them. Business errors come with HTTP status 200, so check the code in the response.

HTTP statuscodeWhenWhat to do
401unauthorizedThe API Key is missing or invalidCheck the header Authorization: Bearer <API Key>; a website login token is not an API Key.
400bad_requestThe body is empty (detail is data is empty), or it was not received completelySend the binary content of the PDF as the body.
200parse_file_too_largeThe body is larger than 300 MiBUse preupload (up to 1 GiB).
200parse_pdf_invalidThe file cannot be opened; it is not a valid PDFCheck locally that the file opens; send the binary content of the file itself as the body.
200parse_file_invalidThe file has no pagesAs above.
200parse_page_limit_exceededThe document has more than 1000 pagesUse preupload (up to 2000 pages), or split the document.
200parse_concurrency_limitThe account is at its limit of tasks or pages in progressSubmit again when running tasks have finished.
200parse_quota_limitThe account's balance or parsing quota is not enoughTop up before submitting again; do not retry in a loop.
500internal_errorA server-side error; also returned when the body has not arrived within 60 secondsSee "Retrying" below; use preupload for large files or slow networks.

With any code other than internal_error, no task was created and nothing is charged. Errors after a successful submission (parsing failed, timed out and so on) are returned by the status query; see Troubleshooting in the PDF reference.

Edge cases

Request body

  • The whole body is taken as the file, so the body should be the binary content of the PDF itself. multipart/form-data is not a supported way to submit and is not guaranteed to parse.
  • An empty body returns HTTP 400 bad_request with detail set to data is empty.
  • Size is counted in bytes of the body; more than 300 MiB returns parse_file_too_large.
  • Pages are checked on submission: a 1000-page document is accepted, 1001 pages return parse_page_limit_exceeded.

Upload time

  • The whole body must arrive within 60 seconds. Past that the submission fails and no task is created: the server answers HTTP 500 internal_error at 60 seconds at the earliest, when the upload may still be in progress. Sending a 300 MiB file in 60 seconds takes about 42 Mbps of upstream bandwidth; use preupload for large files or slow networks.

Retrying

  • This interface has no idempotency mechanism: every successful request creates a new task.
  • After internal_error, a request timeout or a dropped connection it is unknown whether the task was created, and there is no uid to check. Submitting again may leave you with two tasks, each charged when it succeeds.
  • Every other error code means that no task was created; handle it as described under "Error codes" and submit again.

After migrating to preupload

  • An upload URL is for one PUT of this one file, without Authorization; it expires 10 minutes after it is issued and must not be reused.
  • Getting an upload URL checks no file and charges nothing; the task starts once the file has been uploaded.
  • Too many pages (more than 2000), a file that is too large or invalid, and a concurrency limit or balance that does not cover the actual number of pages are all returned as error codes by the status query, so handle responses whose code is not success while polling.
  • From the moment the upload URL is issued until processing starts, a status query returns processing, which is not an error. It also returns processing when the PUT did not succeed, so a failed upload does not show there: make sure the PUT returned HTTP 200 before polling, and give the polling a time to give up.

FAQ

When will direct upload be discontinued

No date has been set. Once it is, it will be announced on this page first, and until then existing calls are not affected. We recommend migrating now rather than waiting for the date.

Does the parsing result change after migration

No. Both ways feed the same parsing service; the result format and the export interfaces are the same.

Does billing change after migration

No. The billing rules and the unit price are the same for both.

Are tasks already submitted by direct upload affected

No. Their uid, status queries, results and exports stay as they are.

Do the image interfaces need migrating

No. The image interfaces are not being deprecated; keep calling them as described in the image reference.