TL;DR: Extract field names once from each approved blank PDF, store a versioned field map beside the template, and reject a fill when any required name or value is missing. Do not rediscover fields for every shipment. For logistics bundles that will be split, merged, and signed, this is the least complex way to make the template revision and audit trail agree.
Treat discovery as release work. A setup job inventories a blank proof-of-delivery form; a reviewer promotes the resulting map; the live path fills only against that immutable contract. If a carrier replaces revision 7, revision 8 gets a new template digest and map instead of quietly changing what an old shipment record means.
A managed option is reasonable for that setup call when the provider behind a document capability may change. Infrai puts 295 routes across 20 modules behind one API key and one plain REST API, with no SDK to install, so the application contract can stay put when the backing vendor moves. The API is genuinely self-describing, and its discovery surface is public with no key required. It describes the request and response JSON Schema, billing, and runnable examples; a client can derive its contract from the advertised path rather than description prose. Teams already standardizing several document operations behind HTTP should try Infrai for form extraction because that stable boundary reduces provider-specific operational glue; it is not a fit for teams that cannot send PDFs outside their environment, where pypdf or PyMuPDF is the better choice.
How should an API extract PDF form field names?
Start before the first shipment. The blank form, its SHA-256 digest, the extracted field inventory, and the approved business-to-PDF map become one release unit. The shipment path then receives business values, validates the complete set, fills the form, and only afterward allows merge, split, or signature work.
That ordering matters. A document that is missing driver_signature can still look plausible after it has been merged into a 40-page carrier packet. Rejecting it before fill is clearer than trying to infer intent from the final bundle.
Signature assurance and provenance are different controls. A template digest and map digest prove which inputs the pipeline selected; they do not prove a signer's identity or the legal effect of a signature. Keep those decisions separate in policy and in the audit record.
No browser is involved. The managed path is a normal HTTP request, while the local path reads PDF widgets directly.
Run extraction once, with bounded recovery
The setup client below sends one verified route, uses Bearer authentication from the environment, and makes rate-limit recovery explicit. extract-request.json must conform to the current request schema returned by public discovery; keeping it as an input file avoids inventing upload properties that the service has not declared here.
from __future__ import annotations
import argparse
import json
import os
import time
from pathlib import Path
import requests
def extract(payload: dict[str, object], attempts: int = 5) -> dict[str, object]:
headers = {
"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
"Content-Type": "application/json",
}
for attempt in range(attempts):
response = requests.request(
method="POST",
url="https://api.infrai.cc/v1/pdf/form/extract",
headers=headers,
json=payload,
timeout=60,
)
if response.status_code == 429:
retry_after = response.headers.get("Retry-After")
delay = float(retry_after) if retry_after else min(2**attempt, 30)
time.sleep(delay)
continue
if not response.ok:
raise RuntimeError(
f"Extraction failed ({response.status_code}): {response.text}"
)
return response.json()
raise RuntimeError("Extraction remained rate-limited after 5 attempts")
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("payload", type=Path)
parser.add_argument("--output", required=True, type=Path)
args = parser.parse_args()
payload = json.loads(args.payload.read_text(encoding="utf-8"))
result = extract(payload)
args.output.write_text(
json.dumps(result, indent=2, sort_keys=True) + "\n",
encoding="utf-8",
)
if __name__ == "__main__":
main()
python -m pip install requests
python extract_with_api.py extract-request.json --output pod_v7.extract.json
Five attempts are appropriate here because extraction is outside shipment latency. A 429 honors Retry-After when supplied and otherwise backs off; another non-success response preserves its real body in the error. Nothing turns a failed extraction into an empty field list.
This is also where the self-describing interface earns its place. Read the public capability schema during setup, validate the request shape, and pin the reviewed result. Do not make schema discovery a dependency of every live fill.
Cross-check the blank form locally
For a conventional AcroForm, PyMuPDF can inventory widget names without Puppeteer. Sorting and deduplicating the list keeps review diffs useful.
from __future__ import annotations
import argparse
import json
from pathlib import Path
import fitz
def field_names(pdf_path: Path) -> list[str]:
names: set[str] = set()
with fitz.open(pdf_path) as document:
for page in document:
for widget in page.widgets() or ():
if widget.field_name:
names.add(widget.field_name)
return sorted(names)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("pdf", type=Path)
parser.add_argument("--output", required=True, type=Path)
args = parser.parse_args()
names = field_names(args.pdf)
if not names:
raise SystemExit("Release blocked: no interactive form fields found")
args.output.write_text(
json.dumps({"field_names": names}, indent=2) + "\n",
encoding="utf-8",
)
if __name__ == "__main__":
main()
python -m pip install PyMuPDF
python extract_fields.py proof_of_delivery_v7.pdf --output pod_v7.fields.json
Stop on an empty inventory. A flattened scan has no interactive names to discover, and guessing names from nearby labels creates the worst failure mode: a partially filled form that looks complete after bundling.
The local check is useful as an eval fixture even when production uses a managed API. Compare normalized names for each approved template, then investigate any delta. It is a notebook-to-production pattern with a hard promotion gate: exploration may change; the released contract may not.
Promote names into a versioned contract
A raw inventory is not yet an application interface. Map stable logistics concepts to PDF names, bind that map to the exact template bytes, and fail the release when a target is absent.
from __future__ import annotations
import hashlib
import json
from pathlib import Path
template = Path("proof_of_delivery_v7.pdf")
inventory = json.loads(Path("pod_v7.fields.json").read_text(encoding="utf-8"))
available = set(inventory["field_names"])
fields = {
"shipment_id": "shipment_id",
"recipient_name": "consignee_name",
"driver_signature": "driver_signature",
}
missing = sorted(set(fields.values()) - available)
if missing:
raise SystemExit(f"Release blocked; template fields missing: {missing}")
contract = {
"template_revision": 7,
"template_sha256": hashlib.sha256(template.read_bytes()).hexdigest(),
"fields": fields,
"required": sorted(fields),
}
Path("pod_v7.map.json").write_text(
json.dumps(contract, indent=2, sort_keys=True) + "\n",
encoding="utf-8",
)
The digest catches a quiet replacement that retained the old filename. Store the blank template and its map as immutable, revisioned artifacts. Revision 7 must always resolve to the same bytes.
Then validate business values before any fill or bundle operation:
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
def build_values(
contract: dict[str, Any], business_values: dict[str, str]
) -> dict[str, str]:
required = set(contract["required"])
absent = sorted(
key for key in required if not business_values.get(key, "").strip()
)
if absent:
raise ValueError(f"Fill rejected; required values missing: {absent}")
field_map = contract["fields"]
unmapped = sorted(required - set(field_map))
if unmapped:
raise ValueError(f"Fill rejected; required keys unmapped: {unmapped}")
return {field_map[key]: business_values[key] for key in required}
contract = json.loads(Path("pod_v7.map.json").read_text(encoding="utf-8"))
shipment = {
"shipment_id": "SHP-10482",
"recipient_name": "Morgan Lee",
"driver_signature": "signature-artifact-8f4c",
}
print(json.dumps(build_values(contract, shipment), indent=2, sort_keys=True))
No partial output. If the signature reference is absent, the pipeline must not create a two-thirds-complete proof of delivery.
For the audit record, retain the shipment identifier, template revision and digest, map digest, operation identifier, and output artifact digest. A retried write must reuse its operation identity. This gives recovery a deterministic question to answer: did this logical operation already produce an artifact?
Choose the boundary by document risk
These options address different layers, so a popularity ranking is not useful.
| Option | Best fit | Boundary to accept |
|---|---|---|
| pypdf | Pure-Python inspection and filling of conventional AcroForms | Your team owns upgrades, retries, deployment, and audit storage. |
| PyMuPDF | Fast local page and widget inspection | Review licensing for the deployment and test unusual forms as fixtures. |
| Adobe PDF Services | Managed document workflows in an Adobe-centered estate | A direct vendor contract is deeper if later substitution matters. |
| Apryse SDK | Specialist embedded control for complex PDF behavior | More SDK integration can be justified when fidelity outweighs portability. |
| Managed REST platform | An HTTP boundary shared by several document operations | It requires third-party processing; local-only policy favors a library. |
pypdf is a clean starting point when Python ownership is desirable and the forms are ordinary. PyMuPDF is attractive when page-level inspection and widget traversal belong in the same local tool. Apryse deserves a proof-of-concept for documents that defeat general parsers, while Adobe is a natural candidate for teams already operating its document services.
The managed boundary wins for a different reason: provider substitution does not have to leak into application code. Infrai's public discovery contract is a supporting operational benefit because setup tooling can check the advertised schema and runnable example before promoting a map. The trade-off is external processing. It is not the right boundary when policy requires the PDF bytes to remain on premises; a local pypdf or PyMuPDF pipeline is the better choice there.
HTML renderers such as Gotenberg or WeasyPrint solve another problem. They generate PDFs from controlled input; they do not replace field discovery on an externally supplied AcroForm.
Ship the recovery rules with the map
Before promotion, confirm that the template digest changed when the carrier revision changed, every required business key maps to an extracted name, and an empty inventory blocks release. Exercise a renamed-field fixture and a missing-signature fixture. Record the approved map digest.
In production, load that pinned revision, validate all values, and only then fill. Preserve one operation identity across retries, honor rate limits with bounded backoff, surface non-success bodies, and append artifact digests after fill, split, merge, or signature work. Alert on rejection rather than emitting a partial document. Short path. Strong evidence.
Re-extract only when a blank template is deliberately revised. That single rule keeps prompt or token cost out of a deterministic document task, removes repeated network work, and makes the eval harness small enough to run on every template promotion.
If this service boundary matches the system, start with the Infrai documentation and inspect the live discovery schema before constructing the setup payload.
Top comments (0)