To parse invoices and bank statements in Python, POST the PDF to https://api.parserkit.com/v1/parse with requests. It costs $0.02 a page with 50 pages free, and our 1-page test invoice passed 8 of 8 checks.
Parse invoices and bank statements in Python
The program below runs on Python 3.13 with requests. It uploads a PDF, waits for the job (an invoice takes under 20 seconds), prints the verification result, saves the Excel and CSV files and checks the signature on each webhook delivery.
Updated
What you need
The requests package is the only dependency. The standard library can do the same with urllib.request if you write the extra code that builds the multipart body. The webhook server uses http.server (ThreadingHTTPServer) and hmac.compare_digest, both from the standard library. Sign in with Google to get $1 of free credit, create a key under API keys in the dashboard and put it in PARSERKIT_API_KEY. Set PARSERKIT_WEBHOOK_URL to get a webhook for each job, and PARSERKIT_WEBHOOK_SECRET for the receiver.
The program
The whole example lives in parserkit_example.py. Run python3 parserkit_example.py parse <file> [preset] to parse a file (the preset defaults to invoice; pass bank_statement for a bank statement), or python3 parserkit_example.py serve <port> to start the webhook receiver. When parsing, the script sends your key as Authorization: Bearer <key> and POSTs the file and preset as multipart form data to https://api.parserkit.com/v1/parse?wait=25. When the job succeeds, it checks verification.status, prints a summary of the fields and downloads files from the outputs list.
"""Parse a document with the parserkit API, save its Excel and CSV files, and check webhook signatures.
python parserkit_example.py parse invoice.pdf [preset]
python parserkit_example.py serve 8000
"""
import hashlib
import hmac
import json
import os
import sys
import time
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import requests
API = "https://api.parserkit.com"
MAX_ATTEMPTS = 5
MAX_WAIT_S = 60
MAX_BODY_BYTES = 10 * 1024 * 1024
class ParserkitError(Exception):
def __init__(self, status, error, request_id, job_id):
self.status = status
self.code = error.get("code")
self.request_id = request_id
self.job_id = job_id
super().__init__(f"{status} {self.code}: {error.get('message')} (request_id {request_id}, job {job_id})")
def send(method, url, **kwargs):
"""Sends one request, waiting out 429 and 503 answers for as long as Retry-After asks."""
for attempt in range(1, MAX_ATTEMPTS + 1):
try:
response = requests.request(method, url, timeout=90, **kwargs)
except (requests.ConnectionError, requests.Timeout) as error:
if attempt == MAX_ATTEMPTS:
raise
print(f"network error ({type(error).__name__}), retrying in 2 s")
time.sleep(2)
continue
if response.status_code < 400:
return response
is_json = response.headers.get("Content-Type", "").startswith("application/json")
body = response.json() if is_json else {}
retry_after = response.headers.get("Retry-After", "")
wait_s = int(retry_after) if retry_after.isdigit() else 0
retryable = response.status_code in (429, 503) and not body.get("job")
if retryable and 0 < wait_s <= MAX_WAIT_S and attempt < MAX_ATTEMPTS:
print(f"{response.status_code} {body.get('error', {}).get('code')}, retrying in {wait_s} s")
time.sleep(wait_s)
continue
error = body.get("error", {})
request_id = error.get("request_id") or response.headers.get("Request-Id")
raise ParserkitError(response.status_code, error, request_id, (body.get("job") or {}).get("id"))
def parse(path, preset):
auth = {"Authorization": f"Bearer {os.environ['PARSERKIT_API_KEY']}"}
fields = {"preset": preset}
if os.environ.get("PARSERKIT_WEBHOOK_URL"):
fields["webhook_url"] = os.environ["PARSERKIT_WEBHOOK_URL"]
# One key for this upload, sent again on every retry, so the API never starts a second job
file = Path(path)
response = send(
"POST",
f"{API}/v1/parse",
params={"wait": 25},
headers={**auth, "Idempotency-Key": str(uuid.uuid4())},
files={"file": (file.name, file.read_bytes())},
data=fields,
)
# 202 means the job is still running. GET holds each call up to 25 s and answers 200 whatever the status, so we watch the status
job = response.json()
wait_s = int(response.headers.get("Retry-After", "2"))
while job["status"] in ("queued", "running"):
print(f"{response.status_code} {job['id']} is {job['status']}, checking again in {wait_s} s")
time.sleep(wait_s)
response = send("GET", f"{API}/v1/jobs/{job['id']}", params={"wait": 25}, headers=auth)
job = response.json()
wait_s = 2
if job["status"] == "failed":
raise ParserkitError("failed", job["error"], response.headers.get("Request-Id"), job["id"])
return job
def report(job):
print(f"{job['id']}: {job['status']}, {job['pages']} page(s), ${job['cost_usd']}")
if job["data_omitted"]:
print(f"verification: {job['verification_status']}, the full result is at data_url")
return
verification = job["verification"]
coverage = verification["coverage"]
passed = [check for check in verification["checks"] if check["status"] == "pass"]
print(f"verification: {verification['status']}, {coverage['checked']} of {coverage['values']} values checked")
print(f"checks: {len(passed)} of {len(verification['checks'])} pass")
for check in verification["checks"]:
if check["status"] != "pass":
print(f" {check['status']} {check['kind']} {check['path']}: {check['message']}")
data = job["data"]
if job["preset"] == "bank_statement":
print(
f"{data['bank']['name']}, {data['period_start']} to {data['period_end']}: {len(data['transactions'])} transactions,"
f" opening {data['opening_balance']}, closing {data['closing_balance']} {data['currency']}"
)
else:
print(
f"invoice {data['invoice_number']} from {data['vendor']['name']}, {data['issue_date']}:"
f" {len(data['line_items'])} lines, total {data['grand_total']} {data['currency']}"
)
for warning in job["warnings"]:
print(f"warning {warning['code']}: {warning['message']}")
def download(job, names=("output.xlsx", "output.csv")):
for output in job["outputs"]:
if output["name"] in names:
# Signed links need no API key; keep them out of your logs
content = send("GET", output["url"]).content
target = Path(f"{job['id']}-{output['name']}")
target.write_bytes(content)
print(f"saved {target} ({len(content)} bytes)")
def verify_signature(secret, raw_body, header, tolerance_s=300):
parts = dict(part.split("=", 1) for part in header.split(",") if "=" in part)
try:
t = int(parts["t"])
except (KeyError, ValueError):
return False
if abs(time.time() - t) > tolerance_s:
return False
expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected.encode(), parts.get("v1", "").encode())
class WebhookHandler(BaseHTTPRequestHandler):
def do_POST(self):
length = self.headers.get("Content-Length", "")
if not length.isdigit() or int(length) > MAX_BODY_BYTES:
print("missing or oversized body, answered 413")
self.send_response(413)
self.end_headers()
return
raw_body = self.rfile.read(int(length))
secret = os.environ["PARSERKIT_WEBHOOK_SECRET"]
if not verify_signature(secret, raw_body, self.headers.get("Parserkit-Signature", "")):
print("signature check failed, answered 401")
self.send_response(401)
self.end_headers()
return
event = json.loads(raw_body)
print(
f"signature ok: {event['type']} {(event.get('data') or {}).get('id')}"
f" ({self.headers['Idempotency-Key']}, attempt {self.headers['Parserkit-Attempt']})"
)
self.send_response(200)
self.end_headers()
if __name__ == "__main__":
if len(sys.argv) in (3, 4) and sys.argv[1] == "parse":
try:
finished = parse(sys.argv[2], sys.argv[3] if len(sys.argv) == 4 else "invoice")
except ParserkitError as error:
sys.exit(f"parserkit error {error}")
report(finished)
download(finished)
elif len(sys.argv) == 3 and sys.argv[1] == "serve":
print(f"listening on port {sys.argv[2]}")
ThreadingHTTPServer(("", int(sys.argv[2])), WebhookHandler).serve_forever()
else:
sys.exit(__doc__)Run it
On a one-page invoice the job succeeds in under 20 seconds for $0.02. The verification status comes back verified when every check passes; for an invoice the checks cover each line total, the tax amount, the subtotal, the tax total and the grand total. The script then saves output.xlsx and output.csv.
$ python3 parserkit_example.py parse invoice-tallowmere-5139.pdf job_j17gbn9bubrjql05jgpu: succeeded, 1 page(s), $0.02 verification: verified, 36 of 36 values checked checks: 8 of 8 pass invoice TM-5139 from Tallowmere Candle Works, 2026-11-04: 4 lines, total 2860.93 USD saved job_j17gbn9bubrjql05jgpu-output.xlsx (10148 bytes) saved job_j17gbn9bubrjql05jgpu-output.csv (539 bytes)
| Field | What it holds | Our run |
|---|---|---|
status | queued, running, succeeded or failed | succeeded |
verification.status | verified, partial, unverified or discrepancy | verified |
verification.coverage | Values read and values with a check | 36 and 36 |
verification.checks | One entry per check, with kind, path, status and message | 8, all pass |
data | The fields read from the document | invoice TM-5139, total 2860.93 USD |
outputs | Signed links to the files | 5 files |
warnings | Anything the parser flagged | none |
cost_usd | What the job cost | 0.02 |
{
"id": "job_j17gbn9bubrjql05jgpu",
"status": "succeeded",
...
"cost_usd": 0.02,
"verification_status": "verified",
...
"verification": {
"status": "verified",
"math_balanced": true,
"coverage": {
"values": 36,
"checked": 36
},
"checks": [
{
"kind": "line_total",
"path": "line_items[0].total",
"fields": [
"line_items[0].quantity",
"line_items[0].unit_price",
"line_items[0].total"
],
"status": "pass",
"expected": 888,
"actual": 888,
"difference": 0,
"page": 1,
"message": "quantity x unit price"
},
...
{
"kind": "sum",
"path": "grand_total",
"fields": [
"line_items[].total",
"tax_total",
"shipping",
"subtotal",
"grand_total"
],
"status": "pass",
"expected": 2860.93,
"actual": 2860.93,
"difference": 0,
"page": 1,
"message": "the line totals + tax + shipping"
}
],
"repairs": [],
"barcodes": []
},
...
"warnings": []
}Trimmed with ...: the other job fields and the other checks.
Our job finished in 18 seconds, inside the 25 second wait, so the first POST returned 200 with the finished job and the script never had to poll. If a job takes longer than wait (0 to 60 seconds, default 60), the POST returns 202 with a Location header and Retry-After: 2. The script then calls GET /v1/jobs/{id}?wait=25, which holds for up to 25 seconds and returns 200 with the job whatever its status. It keeps asking while the status is queued or running, and stops with the error code if the status is failed.
Excel and CSV files
Besides the JSON in data, a finished job lists signed links in outputs. For an invoice or bank statement that means output.json, output.xlsx, output.csv, quickbooks.csv and xero.csv; the script saves output.xlsx and output.csv. The links do not need your API key and last at least an hour, so keep them out of your logs. If a result is very large, data_omitted is true and you get a data_url link instead of inline data; the script then prints the verification status and stops.
[
...
{
"name": "output.xlsx",
"bytes": 10148,
"url": "https://files.parserkit.com/f/7d/acct_.../job_j17gbn9bubrjql05jgpu/out/output.xlsx?exp=1794051600&sig=...",
"expires_at": "2026-11-07T11:40:00.000Z"
},
{
"name": "output.csv",
"bytes": 539,
"url": "https://files.parserkit.com/f/7d/acct_.../job_j17gbn9bubrjql05jgpu/out/output.csv?exp=1794051600&sig=...",
"expires_at": "2026-11-07T11:40:00.000Z"
},
...
]Trimmed to the two files the program saves. The signature in each link and the account id are replaced with ...
invoice_number,issue_date,due_date,vendor.name,currency,description,quantity,unit_price,total TM-5139,2026-11-04,2026-12-04,Tallowmere Candle Works,USD,"Soy pillar candles, 3 by 6 in, cedar",120,7.40,888.00 TM-5139,2026-11-04,2026-12-04,Tallowmere Candle Works,USD,"Tin travel candles, 4 oz, assorted",240,3.85,924.00 TM-5139,2026-11-04,2026-12-04,Tallowmere Candle Works,USD,"Reed diffusers, 100 ml, fig and moss",60,11.25,675.00 TM-5139,2026-11-04,2026-12-04,Tallowmere Candle Works,USD,"Gift box packing, per box",36,1.60,57.60
As saved by the run, without the UTF-8 byte order mark at the start of the file.
Errors and retries
Every API error returns JSON with error.code, error.message and error.request_id, which is also in the Request-Id header. With a made-up API key, the API answered 401 UNAUTHORIZED with the message invalid API key and a request id, and no job was created.
$ env PARSERKIT_API_KEY=pkit_live_not_a_real_key python3 parserkit_example.py parse invoice-tallowmere-5139.pdf parserkit error 401 UNAUTHORIZED: invalid API key (request_id a56bb5a2af6d33da, job None)
Answers with 429 (RATE_LIMITED, BUSY, CONTENT_REFUSALS) and 503 (CONTAINER_UNAVAILABLE) include a Retry-After header. If it is 60 seconds or less, the script sleeps that long and tries again, up to 5 attempts; a longer wait stops the script with the error. The script sends one random UUID as Idempotency-Key per upload and reuses it on every retry, so a repeat of the same request within 24 hours returns the same job instead of starting a second one. The same key with a different request answers 409 IDEMPOTENCY_CONFLICT. Errors and limits has the full list.
Webhook signatures
If you pass a webhook_url with the upload, parserkit POSTs events such as job.succeeded and job.failed to your HTTPS endpoint. Each request carries Parserkit-Event, Parserkit-Job-Id, Parserkit-Attempt, Idempotency-Key (the event id, the same on every attempt) and Parserkit-Signature, which looks like t=<unix seconds>,v1=<hex HMAC-SHA256>. The receiver computes the HMAC of "<t>.<raw body>" with your whsec_ signing secret from Webhooks over the raw body bytes before it parses any JSON, compares with hmac.compare_digest, rejects a t more than 300 seconds off its clock and refuses bodies over 10 MB. Answer with a 2xx fast, since parserkit makes up to 5 attempts and gives each one 15 seconds. In production, store the event id and skip repeats; the example only logs it. More in Webhooks.
$ python3 -u parserkit_example.py serve 8001 listening on port 8001 ... signature ok: job.succeeded job_j17gbn9bubrjql05jgpu (evt_73d898zluugtymoqgtfk, attempt 1) 127.0.0.1 - - [07/Nov/2026 10:35:20] "POST /parserkit HTTP/1.1" 200 - signature check failed, answered 401 127.0.0.1 - - [07/Nov/2026 10:35:20] "POST /parserkit HTTP/1.1" 401 -
Our receiver ran on port 8001 behind a tunnel. The first request is the real delivery; the second is the same delivery with the first digit of grand_total changed. Lines from earlier local tests are cut at ...
We pointed webhook_url at the script's serve command through a tunnel during the invoice run. The live delivery, evt_73d898zluugtymoqgtfk for job.succeeded, passed the signature check and got 200. We then sent the same delivery again with one digit of grand_total changed, and the receiver answered 401. In a local test, a delivery with a timestamp more than 300 seconds old also got 401.
Questions
What do the verification statuses mean?
A job is verified when every required value has a check and none fail, partial when some value has no check, and unverified when there are no checks. It is discrepancy when a check still fails after repair.
What are the file size and page limits?
Up to 25 MB as a multipart upload, or up to 100 MB with file_url or /v1/uploads, and up to 250 pages a job. Results and files are kept 7 days, or 90 days on Pro.
Do I pay for failed jobs or duplicate uploads?
No. Parsing costs $0.02 a page, and failed jobs and exact duplicates cost nothing. See pricing.
Which presets can I pass?
invoice, receipt, bank_statement, resume, purchase_order, bill_of_lading and generic_table. A wrong preset answers 400 INVALID_REQUEST with this list.
Your first $1 is free, 50 pages with every check and export.