Handling PDF Output — base64 vs upload_url

Every PDF processing endpoint (merge, split, rotate, compress, convert, generate…) returns its output in one of two forms, and the form depends on server configuration, not on your request:

Mode Response field What you get
Inline (storage disabled) "pdf": "<base64>" The whole file, base64-encoded, in the JSON body
Storage-backed (storage enabled) "upload_url": "<https://…/v1/pdf/download/…>" A url you fetch separately

The same is true for multi-file outputs: parts[] and images[] entries each carry either pdf/image (base64) or upload_url. Write your client to handle both — this is the single biggest source of "works locally, breaks in staging" bugs against the PDF API.

Base URL: https://pdf.toolkitapi.io Auth: X-API-Key header on processing calls.


Detecting the mode

from dataclasses import dataclass
import base64, os
from typing import Iterable
import httpx

BASE = "https://pdf.toolkitapi.io"
HEADERS = {"X-API-Key": os.environ["TOOLKIT_API_KEY"]}

@dataclass
class PdfArtifact:
    url: str | None = None
    b64: str | None = None

    def save(self, path: str) -> None:
        if self.url:
            r = httpx.get(self.url, timeout=120)
            r.raise_for_status()
            with open(path, "wb") as fh:
                fh.write(r.content)
        elif self.b64:
            with open(path, "wb") as fh:
                fh.write(base64.b64decode(self.b64))
        else:
            raise ValueError("artifact has neither url nor b64")

def artifacts(payload: dict) -> list[PdfArtifact]:
    """Normalise single, multi-part and image outputs into one shape."""
    out: list[PdfArtifact] = []
    if "pdf" in payload or "upload_url" in payload:
        out.append(PdfArtifact(url=payload.get("upload_url"), b64=payload.get("pdf")))
    for part in payload.get("parts", []) or []:
        out.append(PdfArtifact(url=part.get("upload_url"), b64=part.get("pdf")))
    for img in payload.get("images", []) or []:
        out.append(PdfArtifact(url=img.get("upload_url"), b64=img.get("image")))
    return out
function artifacts(payload) {
  const out = [];
  if ("pdf" in payload || "upload_url" in payload) {
    out.push({ url: payload.upload_url ?? null, b64: payload.pdf ?? null });
  }
  for (const part of payload.parts ?? []) out.push({ url: part.upload_url ?? null, b64: part.pdf ?? null });
  for (const img of payload.images ?? []) out.push({ url: img.upload_url ?? null, b64: img.image ?? null });
  return out;
}

async function saveArtifact(artifact, filename) {
  const bytes = artifact.url
    ? new Uint8Array(await (await fetch(artifact.url)).arrayBuffer())
    : Buffer.from(artifact.b64, "base64");
  await require("node:fs/promises").writeFile(filename, bytes);
}

Fetching the file

curl -s -X POST "https://pdf.toolkitapi.io/v1/pdf/merge" \
  -H "X-API-Key: $TOOLKIT_API_KEY" -H "Content-Type: application/json" \
  -d '{"pdfs": ["<base64-a>", "<base64-b>"]}' > out.json

# If storage is enabled:
jq -r '.upload_url' out.json | xargs curl -sSL -o merged.pdf

# If inline:
jq -r '.pdf' out.json | base64 -d > merged.pdf
resp = httpx.post(f"{BASE}/v1/pdf/merge", json={"pdfs": [a_b64, b_b64]},
                  headers=HEADERS, timeout=300)
resp.raise_for_status()
for i, art in enumerate(artifacts(resp.json())):
    art.save(f"merged-{i}.pdf")

The download endpoint

The upload_url points at:

GET /v1/pdf/download/{object_name}

Behaviour worth knowing:

  • object_name is opaque. It is a 32-character UUID hex string plus a validated extension — ^[0-9a-f]{32}\.(pdf|png|jpe?g|webp)$. Do not parse it, construct it, or try to make it human-readable.
  • No X-API-Key is required on the download URL itself; the URL is the credential. Treat it as a secret and never log it in full or render it in HTML unescaped.
  • The response is Content-Disposition: inline, so browsers render PDFs rather than downloading them. Force a download with <a download> or an explicit -o on curl.
  • Files are not permanent. Storage is a scratch space, not an archive — download promptly and store the bytes yourself.
  • Malformed names return 400 Invalid object name before any storage call, so you cannot probe for arbitrary objects.
  • Missing or expired objects return 404 File not found: ….
Status Meaning
200 File bytes, correct Content-Type (application/pdf, image/png, …)
400 Invalid object name — pattern mismatch (wrong length, unrecognised extension, path traversal)
404 File not found — object expired or never written
5xx Storage backend unavailable

Which fields get rewritten

When storage is enabled, the response shape changes silently. The server replaces:

  1. top-level pdf → upload_url (single-file outputs: merge, rotate, compress, watermark…)
  2. parts[].pdf → parts[].upload_url (split output, one entry per range)
  3. images[].image → images[].upload_url (PDF → image rendering, per page)

The key is removed, not duplicated, when the upload succeeds. If an upload fails, the original base64 value is kept — so a response can mix modes. Your normaliser (above) handles this naturally because it reads both fields.

{
  "pages": 2,
  "parts": [
    {"range": "1", "pages": 1, "upload_url": "https://pdf.toolkitapi.io/v1/pdf/download/3f2a…c1.pdf"},
    {"range": "2", "pages": 1, "upload_url": "https://pdf.toolkitapi.io/v1/pdf/download/9b7d…e4.pdf"}
  ]
}

vs. the same call with storage disabled:

{
  "pages": 2,
  "parts": [
    {"range": "1", "pages": 1, "pdf": "JVBERi0xLjQKJcOkw7zDtsOfCjIgMCBvYmoK…"},
    {"range": "2", "pages": 1, "pdf": "JVBERi0xLjQKJcOkw7zDtsOfCjIgMCBvYmoK…"}
  ]
}

Choosing a mode for your architecture

Prefer upload_url when:

  • Outputs are large — base64 inflates payload size by ~33 %, and a 20 MB PDF becomes a 27 MB JSON body.
  • You are behind a proxy or gateway with JSON body limits (Lambda, API Gateway, Cloudflare).
  • You want to hand a file straight to a browser or a job queue without buffering it.
  • You process many files per request (split, to-images).

Prefer base64 when:

  • You need the bytes atomically with the processing response (no second round trip, no expiry window).
  • You are in an air-gapped environment where the storage backend is disabled.
  • You want one request/one failure mode.

You cannot force the mode from the request — it is deployment configuration. Detect and adapt instead.


Tips

  • Never assume .pdf. The download endpoint serves images too (png, jpeg, webp), and the Content-Type header tells you the truth. Sniff it rather than trusting the extension.
  • Stream large downloads (stream=True in httpx, response.body piping in Node) rather than holding whole files in memory.
  • Set a generous read timeout on downloads. A 60 MB file over a slow link will blow a default 5 s timeout; 120 s is a safer floor.
  • Do not retry blindly on 404. An expired object will not come back — re-run the processing call instead.
  • Deduplicate your own storage. Download, write to your bucket with a content hash, then discard the upload_url. You get durability without depending on scratch storage.
  • Log base64 length, never contents. Base64 of a PDF blows up log volume and leaks document contents.
  • Handle mixed responses. If one part uploads and another does not, you get a parts array with both upload_url and pdf keys present. Normalise first, then process.
  • In tests, assert on both shapes. Run your suite once with storage enabled and once disabled; otherwise half your code paths go unexercised.

See also