PDF security blog

Detect PDF Tampering Programmatically: REST Quickstart, Error Contract and Smoke Test

HTPBE Team··13 min read
Detect PDF Tampering Programmatically: REST Quickstart, Error Contract and Smoke Test

This article is a snapshot – content was accurate as of April 2026 (code examples tested against the API as of October 2026). The product evolves actively; specific counts, examples, and detection rules may have changed since publication – see the changelog for the current state.

Your backend accepts a PDF. Somewhere downstream, a person or a rule engine will act on what that file says: approve a loan, pay an invoice, admit a candidate, settle a claim. The cheapest moment to ask ‘has this file been modified since it was created?’ is at ingestion, before anything trusts it.

You do not need to build that check. This guide shows how to call the HTPBE? PDF tamper detection API from any language, read the result, and decide what your system does with each verdict. It is the overview for the whole developer series; the language guides linked below carry the full production code.

Quickstart with curl

You need an API key (the free dashboard also gives you a test key) and a URL the API can download the PDF from: a public link or a presigned URL from S3, Google Cloud Storage, Cloudflare R2 or similar. The file can be up to 10 MB.

Step 1. Submit the document. Analysis runs synchronously and the response contains only the check ID.

curl -X POST https://api.htpbe.tech/v1/analyze \
  -H "Authorization: Bearer $HTPBE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://your-bucket.s3.amazonaws.com/documents/contract.pdf"}'
{"id": "3f9c8b7a-2e1d-4c5f-9b8e-7a6d5c4b3a21"}

Step 2. Read the result.

curl https://api.htpbe.tech/v1/result/3f9c8b7a-2e1d-4c5f-9b8e-7a6d5c4b3a21 \
  -H "Authorization: Bearer $HTPBE_API_KEY"
{
  "id": "3f9c8b7a-2e1d-4c5f-9b8e-7a6d5c4b3a21",
  "filename": "contract.pdf",
  "status": "modified",
  "modification_confidence": "high",
  "modification_markers": ["HTPBE_MULTIPLE_REVISION_LAYERS", "HTPBE_EDITING_TOOL_FINGERPRINT"],
  "has_digital_signature": false,
  "signature_removed": false,
  "modifications_after_signature": false,
  "creator": "Microsoft Word",
  "producer": "iLovePDF",
  "usage_caution": {
    "safe_for_automated_adverse_decision": false,
    "recommended_action": "route_to_human_review",
    "message": "Structural evidence of post-creation modification was found. Route this document to a human reviewer before any decision."
  }
}

The real response carries more fields (page count, dates, algorithm version and others). The abbreviated version above is everything a routing decision needs. The full schema is in the result reference.

You do not need the original file or a known-good copy. You submit only the document under review.

Reading the result

FieldWhat it gives you
statusThe verdict: intact, modified or inconclusive
status_reasonPresent only on inconclusive: why the check does not apply (for example consumer_software_origin, online_editor_origin, scanned_document)
modification_confidencecertain, high or none – how firm a modified verdict is
modification_markersStable machine-readable IDs of what was found, strongest first. Empty unless modified
has_digital_signature, signature_removed, modifications_after_signatureSignature state, as three booleans
usage_caution.recommended_actionThe API’s own routing hint: route_to_human_review, request_from_issuer or no_action

Branch your code on the marker IDs, never on display text. Every ID is stable and prefixed HTPBE_; the dictionary that maps each ID to a plain-language label is published on the How it works page, so you can show reviewers a readable reason without maintaining your own list.

Handling each verdict

statusMeaningWhat your system should do
intactNo evidence of modification, and the file did not come from consumer software, an online editor or a scanContinue the normal flow
modifiedThe file carries evidence that it was changed after it was createdSend to a human reviewer, or ask the sender for a fresh copy from the issuer
inconclusiveThe integrity check does not apply to this kind of fileBranch on status_reason, then decide by document type

Two rules keep the integration honest:

A verdict describes the file, not the person. Every response includes usage_caution.safe_for_automated_adverse_decision: false. Do not auto-reject an applicant, claimant or customer on a verdict alone. modified should open a review, not close a case. certain confidence is the strongest signal the API gives, and it still points to review or a request for a fresh copy from the issuer.

inconclusive is neither a pass nor a failure. It means the file was produced by software that anyone can use to make a document from scratch, or it is a scan, or it is a filled form. Whether that matters depends on what the document claims to be. A bank statement or payslip that arrives from a consumer word processor deserves the same scrutiny as a modified one: ask the issuer to confirm it. A cover letter or a hand-filled application form arriving that way is normal and can proceed.

In pseudocode, the whole decision is a short function:

route(result, claims_institutional_origin):
    if result.status == "modified":      return REVIEW
    if result.status == "inconclusive":
        if claims_institutional_origin:  return VERIFY_WITH_ISSUER
        return CONTINUE
    return CONTINUE

Where the check belongs in your pipeline

  • At ingestion, not at decision time. Run the check when the file arrives (upload handler, email attachment processor, document webhook). By the time a reviewer opens the file, the verdict and markers should already be attached to the record.
  • Store the check ID with the document. Results can be fetched again with GET /v1/result/{id} whenever you need an audit trail, so you do not need to copy the whole payload.
  • Do not block the user’s request on a slow path. A typical analysis finishes in a few seconds, but a queue worker is the right home for it once volume grows. The batch queue guide covers concurrency, backoff and idempotency.
  • Make retries safe. Send an Idempotency-Key header with each submission. If a request times out and you retry with the same key, you get the same check ID back and no second credit is spent.
  • Handle the two transient errors. 429 (server at capacity) carries a Retry-After header; wait that long, then retry. 402 means the account has no credits left, which is a billing event for you, not a document problem.
  • Treat every other 4xx as final. An invalid URL, a file over 10 MB or a file that is not a valid PDF will not succeed on retry. Record the failure and route the document to manual handling.
  • Keep the key on the server. The API key belongs in your backend’s environment, never in a browser or mobile client.

The error contract in one table

Every error body has the same shape (error, code, optionally details), and the code is the stable part. Whatever language you write the client in, this table is the retry policy:

StatuscodeRetry?What your code should do
400invalid_request, invalid_url_formatNoFix the request or the URL; this is a bug on your side
400download_failedOnly if your storage blinkedCheck the URL is public, live and not redirecting; details says which
401missing_api_key, invalid_api_keyNoConfiguration error: alert
402payment_requiredNoOut of credits: alert, pause intake or queue, top up
403inactive_client, account_restrictedNoKey or account disabled: contact support
403test_url_requiredNoA test key was sent a real URL: wrong key in this environment
409idempotency_key_in_progressYes, with the same keyWait for Retry-After; a new key would be a second, charged request
413file_too_largeNoOver 10 MB: compress, or route to manual handling
422invalid_pdf, analysis_timeoutanalysis_timeout may succeedNot a readable PDF, or password-protected; analysis_timeout can be retried
422idempotency_key_fingerprint_mismatchNoThe key was reused for a different URL: one key per document
429server_at_capacityYes, after Retry-AfterServer-wide limit, not a per-key quota; back off
500internal_errorYes, with backoffTransient; escalate if it persists

Two rows matter more than the rest. 402 and 401 both mean the same failure repeats for every document behind this one, so they should stop a batch and notify someone instead of filling a log. And download_failed is a 400, not a 422, because the input your client supplied (the URL) could not be fetched; do not write a 422 branch for it.

Pick where the call runs

The two-call flow does not change, but where you put it does. Four shapes cover nearly every integration:

ShapeUse it whenWatch forGuide
Inline in the upload requestLow volume, a person waiting, a spinner is acceptable2–5 s of latency in the request, and function time limits on serverless hostsNext.js
Background job per documentUploads fan out, or latency in the request is not welcomePersist the idempotency key with the URL it was sent withLaravel, Python
Queue with a bounded worker poolThousands of documents, backfills, shared credit poolServer-wide 429, 402 pausing the queue, content-hash dedupQueue patterns
Event-driven callbackAnother system needs to react when the verdict is readyThe API has no outbound webhook, so the callback is one you fire after your worker reads the resultEvent-driven layer

If you are unsure, start with the background job. It is the smallest shape that keeps the upload request fast, and it grows into the queue without a rewrite.

Test without real documents

Every account has a test key (htpbe_test_...). It accepts only mock URLs such as https://api.htpbe.tech/v1/test/clean.pdf, modified-high.pdf and inconclusive.pdf, returns fixed results and spends no credits. That lets your test suite exercise every verdict branch deterministically. Keep the test key out of production configuration. The full URL list is in the testing guide, and Testing a PDF Verification Integration with Test Keys walks through every mock.

Smoke-test your integration in a minute

Before any language-specific code, prove that the key, the network path and your reading of the verdicts work. This script posts four of the documented mock URLs with a test key, reads each result, and fails loudly if a status is not the one the mock guarantees. It spends no credits and needs only curl and jq:

#!/usr/bin/env bash
set -euo pipefail
: "${HTPBE_TEST_API_KEY:?export your htpbe_test_ key first}"
API=https://api.htpbe.tech/v1
AUTH="Authorization: Bearer $HTPBE_TEST_API_KEY"

expect() { # mock-name expected-status
  id=$(curl -sS -X POST "$API/analyze" -H "$AUTH" -H "Content-Type: application/json" \
        -d "{\"url\": \"$API/test/$1.pdf\"}" | jq -r .id)
  got=$(curl -sS "$API/result/$id" -H "$AUTH" | jq -r .status)
  if [ "$got" = "$2" ]; then echo "ok    $1 -> $got"; else echo "FAIL  $1: wanted $2, got $got"; exit 1; fi
}

expect clean intact
expect modified-high modified
expect signature-removed modified
expect inconclusive inconclusive

# The out-of-credits path, on demand and without touching a real balance.
code=$(curl -s -o /dev/null -w '%{http_code}' -X POST "$API/analyze" -H "$AUTH" \
        -H "Content-Type: application/json" -d "{\"url\": \"$API/test/trigger-402.pdf\"}")
[ "$code" = 402 ] && echo "ok    trigger-402 -> 402" || { echo "FAIL  trigger-402: got $code"; exit 1; }

# A real URL must be refused for a test key.
code=$(curl -s -o /dev/null -w '%{http_code}' -X POST "$API/analyze" -H "$AUTH" \
        -H "Content-Type: application/json" -d '{"url": "https://example.com/real.pdf"}')
[ "$code" = 403 ] && echo "ok    real URL on test key -> 403" || { echo "FAIL  expected 403, got $code"; exit 1; }

If it prints six ok lines, the path from your machine to the API works and you know what each of the three verdicts, the 402 branch and the test_url_required mistake look like on the wire. The same assertions are what your CI suite should carry in your own language; the guides below show how. Test keys are deterministic by design, so this script is safe to run on every deploy. Keep the live key out of it.

Language guides

Pick the guide for your stack. Each one has a complete client, typed result handling, retry logic and a worked example.

StackGuide
Node.js / TypeScriptNode.js integration guide
Python (requests, Django, Flask)Python integration guide
GoGo integration guide
PHP / LaravelLaravel and PHP integration guide
Next.js App RouterNext.js integration guide
High volume, background jobsAsync queue patterns
Java / Spring BootSpring Boot integration guide
C# / ASP.NET CoreASP.NET Core integration guide
Ruby on RailsRails integration guide
PHP / SymfonySymfony integration guide
RustRust integration guide
Python (httpx, FastAPI, Celery)Python tutorial

What the check does not cover

The API reports whether the file shows evidence of modification. It does not read or judge what the document says, and it does not validate the cryptographic strength of a signature. A document fabricated from scratch with ordinary software, with nothing edited afterwards, is not something this kind of check can call fake. That is why inconclusive exists and why institutional documents from consumer software should be confirmed with the issuer. Password-protected files must be unlocked before submission.

Pricing and access

Checks draw from one credit pool shared by the API and the web app: a monthly subscription quota, plus optional one-time credit packs. See pricing for plans and pack sizes, and the API page to get a key and start with the test key before you provision a live one.

Frequently Asked Questions

Do I need the original PDF to check for tampering through the API?

No. You submit only the document under review. There is no baseline to upload, which is what makes it practical to run on every inbound file at submission time.

What is the difference between modified and inconclusive?

modified means the file carries evidence of change after creation, and the specific findings are listed in modification_markers. inconclusive means the check does not apply to this kind of file, for example one made with consumer software, an online editor or a scanner. The status_reason field says which. Route them differently depending on whether the document claims to come from an institution.

Can I reject a document automatically on a modified verdict?

The API advises against it. Each response states that the verdict alone is not safe for an automated adverse decision about a person. Use it to send the case to a reviewer or to ask the sender for a fresh copy from the issuer.

How do I test the integration without spending credits?

Use the test key with the mock URLs. Each URL returns a fixed verdict, so you can cover the intact, modified and inconclusive branches in CI without real files or quota.

Which language should I start with?

Any that can send an HTTPS request. The two-call flow is identical everywhere; the guides above only differ in client code, typing and retry idioms.

Share this article

Found this article helpful? Share it with others to spread knowledge about PDF security and fraud detection.

https://htpbe.tech/blog/detect-pdf-tampering-programmatically

Secure your workflow

Create your account – check PDFs on the web or with an API key, both ready on signup.
No sales call. Cancel any time.