To call a document extraction API from Python, open an HTTP client with a timeout, read the API key from the environment, post the tax PDF as a file upload, and parse the JSON response into typed objects with decimal amounts. Test against fictional forms and recorded responses, and treat flagged fields as unconfirmed.
All code in this guide is an illustrative example against a placeholder URL, https://api.example.com. Schema Tax has no public API documentation, so the endpoint path, field names and response shape below are made up to show the pattern, not copied from any real service.
Setting up a document extraction API Python client
A document extraction API Python client needs three things before it sends a file: an HTTP library, an API key loaded from the environment rather than from source code, and explicit timeouts. Most of the work in a reliable client is in those defaults, not in the upload call itself.
Choosing httpx or requests
Two libraries cover most Python HTTP work: requests and httpx. Both send multipart file uploads with a files= argument. httpx adds an async client and a mock transport for tests, which this guide uses later. If your project already depends on requests, the same pattern carries over with small changes.
Timeouts
The two libraries differ in one default that matters for document uploads. The requests advanced usage documentation on timeouts says that by default, requests do not time out unless a timeout value is set explicitly, and that without one your code may hang for minutes or more. The httpx timeouts documentation says httpx raises a TimeoutException after 5 seconds of network inactivity by default.
Neither default fits a tax PDF. A request with no timeout can hang a worker. A five-second read timeout can fail on a multi-page scan that takes the server longer to read. Set a short connect timeout and a longer read timeout, sized to the largest file you expect to send synchronously.
Keys from the environment
The API key belongs in an environment variable or a secrets manager, not in the repository. Read it once when the client is created, and fail with a clear message if it is missing. That way a misconfigured deploy stops at startup instead of sending unauthenticated requests.
# Illustrative client against a placeholder URL. Endpoint and fields are examples.
import os
import httpx
BASE_URL = os.environ.get("EXTRACTION_API_URL", "https://api.example.com")
def make_client() -> httpx.Client:
key = os.environ.get("EXTRACTION_API_KEY")
if not key:
raise RuntimeError("EXTRACTION_API_KEY is not set")
return httpx.Client(
base_url=BASE_URL,
headers={"Authorization": f"Bearer {key}"},
timeout=httpx.Timeout(60.0, connect=5.0),
)
Sending a tax PDF from Python and reading the typed JSON
Sending a tax PDF from Python means posting the file bytes as a multipart upload and reading back a JSON body. Reading the typed JSON means turning that body into dataclasses whose amounts are Decimal values and whose flags are kept, so downstream code cannot ignore them by accident.
The example response below is invented for this guide. It shows one fictional W-2 with three boxes. A real service will use its own field names and structure.
{
"document_id": "doc_example_001",
"pages": 1,
"forms": [
{
"form_type": "W-2",
"tax_year": 2025,
"page": 1,
"fields": {
"employee_ssn": {"value": "XXX-XX-1234", "flagged": false},
"box_1_wages": {"value": "52340.17", "flagged": false},
"box_2_federal_withheld": {"value": "6120.40", "flagged": true}
}
}
]
}
The client code reads that shape into dataclasses. Amounts are sent as strings in this example and converted with Decimal, and parse_float=Decimal guards against a service that sends bare JSON numbers.
# Illustrative only: placeholder URL, example endpoint and field names.
import json
from dataclasses import dataclass
from decimal import Decimal
from pathlib import Path
@dataclass(frozen=True)
class Field:
value: str | Decimal | None
flagged: bool
@dataclass(frozen=True)
class Form:
form_type: str
tax_year: int
page: int
fields: dict[str, Field]
def parse_form(raw: dict) -> Form:
fields = {}
for name, f in raw["fields"].items():
value = f["value"]
if name.startswith("box_") and value is not None:
value = Decimal(str(value))
fields[name] = Field(value=value, flagged=bool(f["flagged"]))
return Form(raw["form_type"], int(raw["tax_year"]), int(raw["page"]), fields)
def extract(client, pdf: Path) -> list[Form]:
with pdf.open("rb") as fh:
resp = client.post("/v1/extract", files={"file": (pdf.name, fh, "application/pdf")})
resp.raise_for_status()
body = json.loads(resp.text, parse_float=Decimal)
return [parse_form(f) for f in body["forms"]]
if __name__ == "__main__":
from client import make_client # the function from the setup section
with make_client() as c:
for form in extract(c, Path("sample-w2.pdf")):
print(form.form_type, form.tax_year, form.fields["box_1_wages"])
A few choices in that code are worth keeping in your own client. The file is opened in binary mode, which the requests documentation on multipart file uploads strongly recommends, because the library may set Content-Length from the byte count. The response is parsed with parse_float=Decimal, which the Python json module documentation describes as a way to parse JSON floats into types such as decimal.Decimal. And raise_for_status() turns an HTTP error into an exception before any parsing starts.
Check the form before you read its fields
Each form in the response carries a form type, a tax year and a page number. Check them before you touch a single box. A client that expects a W-2 and receives a 1099-INT should stop and say so, not look up box_1_wages and crash on a missing key. A client that expects the 2025 tax year and receives a 2024 form has found a stale upload, which is worth a warning to whoever sent it. These two checks cost a line each and catch mix-ups that no amount of field parsing will.
Log pages per request
The example response also reports how many pages the service read. Log that number with the document ID, the file name and the time of the call. Over a month, the log shows how many pages your code actually sent, which is the figure a per page bill is built from. It also shows outliers early: a file that was expected to be one page and came back as twelve is usually a scan with blank backs or a merged PDF, and both are cheaper to fix before upload than after.
Multipart or base64
The upload here is a multipart form. Some APIs take a base64 string inside a JSON body instead. The comparison of multipart and base64 uploads explains the trade-offs in size and memory.
Large PDFs may not come back in one response. Many document APIs accept the file, return a job ID, and send the result later to a webhook. The guide to async document processing and webhooks covers that flow, including how to verify the callback.
How do you test a document extraction API in Python with fictional tax forms?
You test a document extraction API in Python with fictional tax forms by building a small set of made-up documents, saving the API's responses to them as fixtures, and running your parsing code against those fixtures without network calls. Real taxpayer documents never belong in a test suite or a repository.
Building test data for tax form extraction
Good test data for tax form extraction is fictional but realistic. Fill a blank IRS form with invented names, addresses and amounts, and use masked identifiers such as XXX-XX-1234. The IRS General Instructions for Forms W-2 and W-3 say employers may truncate an employee's SSN on employee copies by replacing the first five digits with Xs or asterisks, so a masked SSN is both safe and realistic.
Make the amounts internally consistent. The same W-2 instructions show Box 4, social security tax withheld, as 6.2% of Box 3, social security wages, and describe Medicare tax at 1.45%. A fictional W-2 with Box 3 of $52,340.17 should carry about $3,245.09 in Box 4, so that any validation logic in your code has something correct to pass. Then make a second copy with a deliberate error, such as a Box 4 that is off by a dollar, to prove the check fails.
Cover the shapes that break parsers, not only the clean case:
- A clean, digital W-2 PDF.
- The same W-2 as a phone photo, slightly tilted.
- A PDF with two forms on separate pages, such as a W-2 and a 1099-NEC.
- A form with an empty box, to confirm your code accepts
null. - A response with a flagged field.
Fixtures and recorded responses
The pytest fixtures documentation explains that test functions request fixtures by declaring them as arguments. A fixture can return a client wired to a fake transport. The httpx transports documentation describes httpx.MockTransport, which takes a handler function and returns pre-determined responses.
# test_extract.py: illustrative test against a recorded example response.
import json
from decimal import Decimal
from pathlib import Path
import httpx
import pytest
from extract import extract
FIXTURE = Path(__file__).parent / "fixtures" / "w2_fictional_response.json"
@pytest.fixture
def fake_client():
recorded = json.loads(FIXTURE.read_text())
def handler(request: httpx.Request) -> httpx.Response:
assert request.url.path == "/v1/extract"
return httpx.Response(200, json=recorded)
return httpx.Client(base_url="https://api.example.com",
transport=httpx.MockTransport(handler))
def test_reads_wages_as_decimal(fake_client, tmp_path):
pdf = tmp_path / "w2-fictional.pdf"
pdf.write_bytes(b"%PDF-1.7 placeholder")
forms = extract(fake_client, pdf)
wages = forms[0].fields["box_1_wages"]
assert wages.value == Decimal("52340.17")
assert forms[0].fields["box_2_federal_withheld"].flagged is True
The fixture file is the example JSON from the previous section, saved once. Record it from a real call against a fictional PDF, strip anything you would not commit, and check it in. When the API changes, record again and let the diff show what moved.
How should a Python client handle document extraction API errors?
A Python client should handle document extraction API errors by status code group: fix and stop on 4xx client errors, back off and retry on 429 and most 5xx errors, and retry timeouts only if the upload is safe to repeat. Every retry needs a cap, a delay that grows, and a log line.
Status codes to act on
A 400 or 422 response usually means the request was wrong: a missing file field, an unsupported file type or a corrupt PDF. Retrying sends the same bad request, so log the response body and stop. A 401 or 403 means the key is wrong or lacks access. The MDN reference for 413 Content Too Large says that status means the request was larger than the limits the server defines, so split or compress the file instead of retrying.
A 429 means slow down. The MDN reference for 429 Too Many Requests says the client has sent too many requests in a given time, and that a Retry-After header may say how long to wait. Honor that header when it is present.
Backoff
A 500, 502, 503 or 504 response, and a connection error, can be transient. Retry with exponential backoff: wait one second, then two, then four, with a little random jitter, and give up after a few attempts.
# Illustrative retry wrapper. Placeholder endpoint; tune limits to your API's terms.
import random
import time
import httpx
RETRYABLE = {429, 500, 502, 503, 504}
def post_with_retry(client, path, *, files, attempts=4):
for attempt in range(attempts):
try:
resp = client.post(path, files=files)
except httpx.TransportError:
if attempt == attempts - 1:
raise
else:
if resp.status_code not in RETRYABLE:
return resp
if attempt == attempts - 1:
return resp
wait = resp.headers.get("Retry-After")
if wait and wait.isdigit():
time.sleep(int(wait))
continue
time.sleep(2 ** attempt + random.random())
The file handle in files is consumed by the first attempt, so a real client reopens the file, or reads the bytes once, before each try.
Timeouts and double billing
A read timeout is the hardest case. The server may have finished reading the PDF after your client gave up. If the API bills per page, a blind retry can bill the same pages twice. Send an idempotency key if the API supports one, and check the guide to per page pricing for a document OCR API for how retries show up on a bill.
Python document extraction API mistakes: floats and ignored flags
The two most common Python document extraction API mistakes are parsing money as float and ignoring the flag that marks an uncertain field. The first makes totals drift by fractions of a cent. The second stores a value the service itself was not sure of, as if it had been confirmed.
Money parsed as float
A plain json.loads call turns every JSON number with a decimal point into a float, because the Python json documentation says the default for parse_float is equivalent to float(num_str). Pass parse_float=Decimal to json.loads, or have the API send amounts as strings. The comparison of decimal and float for money in JSON shows the drift with runnable snippets. A related slip is Decimal(float_value), which keeps the binary error in full; always build a Decimal from the string.
Flags dropped on the way to the database
A flag says the service could not read a value with confidence. A client that copies only value into a database throws that information away. Keep the flag next to the value, route flagged forms to a person, and store them as unconfirmed until someone checks the box against the image. Schema Tax works this way in its own interface: uncertain boxes are flagged on an editable view of the form for a person to confirm, as the five steps from upload to export describe.
Other slips worth a test
- Matching on box numbers instead of field names. Box numbers repeat across forms: W-2 Box 1 is wages, while the IRS Instructions for Forms 1099-MISC and 1099-NEC label 1099-NEC Box 1a as nonemployee compensation.
- Assuming one form per PDF. A single file can hold several forms of different types and years, so loop over every form in the response.
- Skipping validation after parsing. Recompute totals and check identifier patterns in your own code too. The guide to validating tax form data lists the checks.
- Committing a real document as a test fixture. Use fictional forms only.
For the same client written in TypeScript, with streaming uploads and a runtime schema check, see the document extraction API guide for Node JS.