OffenderSearch
Developer guide · Python 3.9+

Using a background check API in Python.

One requests.post searches 58 sex offender registries, a second one searches criminal court, jail, prison and warrant records, and both answer in one round trip. First call in about two minutes on a sandbox key; $0.15 a call in production after 25 free ones.

25 free calls · no card

Updated November 8, 2026 · API changelog

POST /v1/search · sandbox
import os
import requests

BASE = os.environ.get("OFFENDERSEARCH_BASE", "https://sandbox.offendersearch.app")

r = requests.post(
    f"{BASE}/v1/search",
    headers={"X-API-Key": os.environ["OFFENDERSEARCH_TEST_KEY"]},
    json={
        "query": {
            "firstName": "Exact",
            "lastName": "Match",
            "dob": "1980-01-01",
        },
    },
    timeout=30,
)
body = r.json()

print(r.headers["X-Offendersearch-Environment"])  # sandbox
print(body["sandbox"])                     # True
print(body["records"][0]["matchState"] if body["records"] else "no records")
One strong match: DOB-verified (matchState dob_match), high confidence, photo, offense, registry state and two addresses.Sandbox people are synthetic; production answers have the same shape.
01

Your first background check in Python: a hit and a clear

Fifteen lines of requests, no client library, and the three outcomes a reviewer needs.

POST /v1/search takes a query object and answers with the records that match it. The function below sends a first name, a last name and, when you hold one, a full date of birth, then reads two things before it looks at a single record: status and counts.sourcesIncomplete. A registry that did not finish makes the answer a lower bound, so the function returns incomplete rather than clear. Only after that does it ask whether any record carries matchState: "dob_match", which is the one state that means the registry published the same full birth date you sent.

The two calls at the bottom are the sandbox’s documented test people. “Exact Match” with the date 1980-01-01 returns one Ohio record at confidence 0.9; “Clear Visitor” returns a complete answer with zero records, which is what most production searches look like. Swap the host for https://api.offendersearch.app and an os_live_ key and nothing else changes. The request and response are walked line by line in the RESTful API example, and the hero block above runs the same request with your own test key.

import os, requests

BASE = "https://sandbox.offendersearch.app"      # os_test_ key. Live keys: https://api.offendersearch.app
HEADERS = {"X-API-Key": os.environ["OFFENDERSEARCH_TEST_KEY"]}

def check(first, last, dob=None):
    query = {"firstName": first, "lastName": last, **({"dob": dob} if dob else {})}
    r = requests.post(f"{BASE}/v1/search", json={"query": query}, headers=HEADERS, timeout=45)
    r.raise_for_status()
    data = r.json()
    if data["status"] != "complete" or data["counts"]["sourcesIncomplete"]:
        return "incomplete"                       # a registry did not finish: not clear, not a hit
    verified = [x for x in data["records"] if x["matchState"] == "dob_match"]
    return "match" if verified else "review" if data["records"] else "clear"

print(check("Exact", "Match", "1980-01-01"))     # match
print(check("Clear", "Visitor"))                 # clear

A query with only a surname, or only a state, is refused with a 422 before anything runs; the search reference lists which combinations are accepted, and the background check API tutorial builds this function into a small service.

02

Typing the Python response: a TypedDict for the record

Field names copied from the captured sandbox answer, so your editor knows what a record holds.

The API returns JSON, and Python will happily treat it as a pile of dictionaries. A TypedDict costs nothing at runtime and gives you completion and type checking for the fields that are actually there. The classes below name every key in the record the hero shows: the identifiers (recordId, personRef), the match fields (matchState, matchConfidence, matchBasis, unverified), the person (name, dob, sex, age), the registry fields (registrationState, addresses, offenses, stateData, flags, images) and the provenance in sources. A key is always present; the registry that publishes nothing for it sends an empty string or null, never a missing key, so rec["offenses"][0] is the only index you need to guard.

matchState is the field your code should branch on, and its values are a short, closed list. dob_match means the full date agreed; year_match means the registry publishes a birth year only and it agreed; age_match means an age fit your date within a year; dob_near_match appears only when you opt in with dobTolerance and a likely typo was kept; None means you sent no date, so nothing was checked. The matching reference defines each one, and date of birth matching covers the tolerance option. If you prefer runtime validation, the same field list drops into a pydantic.BaseModel unchanged.

from typing import Literal, Optional, TypedDict

# Every key below is in the sandbox answer for "Exact Match"; production answers carry the same keys.
MatchState = Literal["dob_match", "year_match", "age_match", "dob_near_match", "no_dob_age_year"]

class Name(TypedDict):
    first: str; middle: str; last: str; suffix: str; full: str

class Address(TypedDict):
    type: str; line1: str; city: str; county: str; state: str; zipcode: str
    lat: Optional[float]; lng: Optional[float]

class Offense(TypedDict):
    crime: str; statute: str; tier: str; convictionDate: str; offenseDate: str
    registrationDate: str; releaseDate: str; caseNumber: str; victimAge: str; convictionCounty: str

class RegistryRecord(TypedDict):
    recordId: str; personRef: str; recordType: Literal["sex_offender"]
    matchState: Optional[MatchState]        # None when you sent no dob: nothing was checked
    matchConfidence: float; matchBasis: list[str]; unverified: bool
    name: Name; dob: str; birthYear: Optional[int]; dobPrecision: str; age: str; sex: str
    registrationState: str; addressStates: list[str]
    addresses: list[Address]; offenses: list[Offense]
    stateData: dict[str, object]; flags: dict[str, bool]
    images: list[dict[str, str]]; sources: list[dict[str, object]]

class Counts(TypedDict):
    records: int; recordsReturned: int
    sourcesQueried: int; sourcesComplete: int; sourcesIncomplete: int

class SearchResponse(TypedDict):
    searchId: str; status: Literal["complete", "partial"]
    counts: Counts; records: list[RegistryRecord]; warnings: list[str]; capped: bool

def triage(res: SearchResponse) -> tuple[list[RegistryRecord], list[RegistryRecord], bool]:
    confirmed = [r for r in res["records"] if r["matchState"] == "dob_match"]
    review = [r for r in res["records"] if r["matchState"] != "dob_match"]
    unfinished = res["status"] == "partial" or res["counts"]["sourcesIncomplete"] > 0
    return confirmed, review, unfinished
matchStateWhat the registry publishedWhat triage() does with it
dob_matchA full date of birth equal to yoursPuts the record in confirmed
year_matchA birth year only, and it agreesPuts the record in review
age_matchAn age that fits your date within a yearPuts the record in review
dob_near_matchA date one typo away, kept because you set dobToleranceReview, always unverified
NoneNothing was compared: your query had no dobReview, as a name-only lead

The whole record, field by field, is the record object reference; background check API response explained reads one captured answer top to bottom.

03

Criminal records in Python: paging through court, jail and warrant hits

The same key on POST /v1/criminal/search, with page and perPage at the top level of the request.

Criminal records live on a second endpoint because they have a different shape: no photograph or tier, a recordType that says whether the row is a court_case, a jail_booking, a doc_inmate record or a warrant, and a cases list whose charges carry severity, plea and disposition. The generator below walks a search page by page: perPage accepts 1 to 200, the response reports totalPages, and a page past the last one returns an empty records list rather than an error. A name with a full date of birth rarely needs a second page; a bare common surname can.

The felony test person returns one closed Ohio case with a guilty plea on the burglary count and a dismissed theft count, which is why the loop prints the disposition beside each charge instead of summarising the case: a booking is not a conviction, and a dismissed charge is not a conviction either. The criminal record reference names every field, the pagination page covers the capped flag at 4,000 records, and the criminal records API page lists the jurisdictions behind the endpoint by state.

def criminal_records(query, per_page=100):
    """Every record for a query, page by page. perPage is 1-200 and sits at the top level."""
    page = 1
    while True:
        r = requests.post(f"{BASE}/v1/criminal/search", headers=HEADERS, timeout=45,
                          json={"query": query, "page": page, "perPage": per_page})
        r.raise_for_status()
        data = r.json()
        yield from data["records"]
        if page >= data["totalPages"]:
            return
        page += 1

for rec in criminal_records({"firstName": "Felony", "lastName": "Record", "dob": "1975-06-15"}):
    print(rec["recordType"], rec["currentStatus"], rec["matchState"])
    for case in rec["cases"]:
        for charge in case["charges"]:
            print("  ", case["caseNumber"], charge["description"], charge["severity"], charge["disposition"])
# court_case on_probation dob_match
#    SBX-CR-2015-000123 Burglary felony Guilty
#    SBX-CR-2015-000123 Theft misdemeanor Dismissed

lastName is required on this endpoint and a first name, date of birth or state narrows within it; search criminal records by name and DOB explains why the surname is the anchor.

04

Batch background checks from a Python list or DataFrame

One POST /v1/batch for up to 1,000 people, answered in input order.

When the people are already in a list, a CSV or a DataFrame, send them together. The body is either a JSON array of query objects or an envelope {"queries": […]} whose other keys, match among them, apply to every row. Each result carries the index of the row it answers, so you join on position and never on a name. A row that fails validation comes back in place with status: "error" and a sentence; the other rows still run. A batch is billed per row at the same rate as single calls, and it is served from the current snapshot, so live re-verification is a single-search option, not a batch one.

From pandas: df[["firstName", "lastName", "dob"]].to_dict("records") produces the list, chunked at 1,000. The batch reference documents the CSV body form and the per-row clearance fields, and bulk background check from a CSV is the worked example.

people = [
    {"firstName": "Clear", "lastName": "Visitor"},
    {"firstName": "Exact", "lastName": "Match", "dob": "1980-01-01"},
]                                                   # up to 1,000 rows a call

r = requests.post(f"{BASE}/v1/batch", headers=HEADERS, timeout=300,
                  json={"queries": people, "match": "balanced"})
r.raise_for_status()
for row in r.json()["results"]:                      # input order; row["index"] is your list position
    person = people[row["index"]]
    if row["status"] == "error":
        print(person["lastName"], "refused:", row["error"])
        continue
    print(person["lastName"], row["status"], row["counts"]["records"])
# Visitor complete 0
# Match complete 1
05

Error handling in Python: 422, 429 and Retry-After

Which statuses to retry, which to show the user, and what the error body looks like.

Every error has a JSON body with one key, detail, in one of three shapes. On a 401, 402 or a refused 422 it is a sentence you can show as-is. When a field fails validation it is a list of {loc, msg, type} entries. On a 429 it is an object with a code (rate_limited or overloaded), a message and retryAfterSeconds, which always equals the Retry-After header. A 429 means the request was not run and not billed; waiting the stated seconds and sending the same body is the whole fix.

The retry set is small on purpose: 429, 502, 503 and 504, plus a dropped connection. A 400, 401, 402 or 422 will answer the same way however many times you send it. The wrapper below honours Retry-After when it is present and otherwise backs off exponentially with jitter, capped at 30 seconds. On the sandbox the limits are fixed, 60 calls a minute and 2,000 a day per test key, so a tight loop will exercise this code path before you go live. Production has no published per-key ceiling; a 429 arrives when the service is at capacity, which is why bursts are the thing to avoid and a worker pool or a batch is the thing to prefer.

import random, time

RETRYABLE = {429, 502, 503, 504}            # 400, 401, 402 and 422 are final: the request itself is wrong

class ApiError(Exception):
    def __init__(self, status, detail):
        super().__init__(f"{status}: {detail}")
        self.status, self.detail = status, detail

def post(path, body, attempts=4):
    for attempt in range(attempts):
        r = requests.post(f"{BASE}{path}", json=body, headers=HEADERS, timeout=45)
        if r.ok:
            return r.json()
        if r.status_code in RETRYABLE and attempt < attempts - 1:
            wait = r.headers.get("Retry-After")                       # seconds; nothing ran, nothing billed
            time.sleep(float(wait) if wait else min(2 ** attempt, 30) + random.random())
            continue
        detail = r.json().get("detail")       # a sentence, a list of {loc, msg, type}, or {"code": ...}
        raise ApiError(r.status_code, detail)

try:
    post("/v1/search", {"query": {"lastName": "Visitor"}})      # a surname alone is refused
except ApiError as e:
    print(e.status, e.detail)                                     # 422 and a sentence you can show a user
Statusdetail shapeIn Python
401A sentence: the X-API-Key header is missing or wrongFix the key; never retry
402A sentence: the free calls are used or there is no active subscriptionAdd billing in the dashboard
422A sentence (query too broad) or a list of {loc, msg, type}Fix the request; show the sentence
429{code, message, retryAfterSeconds}Sleep Retry-After, resend the same body
504{code: "incomplete_no_results", unfinishedSources}Retry, or raise deadlineMs

Every status and both envelopes: errors reference; the reasoning and a curl-only version: rate limits, retries and idempotency and API errors, explained.

06

Verifying a background check webhook in Python with hmac

Monitor alerts and FCRA events arrive signed in X-Offendersearch-Signature; twelve lines check them.

A monitor is a standing watch on a person that posts to your URL when a matching record appears, changes or is removed. Each delivery carries X-Offendersearch-Signature: t=<unix>,v1=<hex>, where v1 is HMAC-SHA256 keyed with the monitor’s webhookSecret over the string "<t>." + raw body. The secret is shown once, on the 201 that created the monitor, and can be rotated with POST /v1/monitors/{id}/webhook-secret. FCRA partner events use the same scheme with the partner endpoint’s secret, so one verifier serves both.

Three details matter in Python. Verify the exact bytes FastAPI gives you from await req.body(); a dict that has been parsed and dumped again will not match. Use the timestamp from the header, not your clock, to rebuild the string, and refuse a t more than five minutes away, which is the replay window. Compare with hmac.compare_digest, which runs in constant time. The body of a monitor delivery has type: "monitor.alert", an event of new, changed or removed, and an alertId to de-duplicate on; the async search endpoint’s webhookUrl is the one unsigned callback, authenticated by a token in the URL instead, as async and webhooks explains.

import hmac, hashlib, json, os, time
from fastapi import FastAPI, HTTPException, Request

app = FastAPI()
SECRET = os.environ["OFFENDERSEARCH_WEBHOOK_SECRET"]   # whsec_… from the 201 that created the monitor

def verify(header: str, body: bytes, tolerance: int = 300) -> bool:
    parts = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
    t, given = parts.get("t", ""), parts.get("v1", "")
    if not t.isdigit() or abs(time.time() - int(t)) > tolerance:
        return False                                      # outside the five-minute replay window
    expected = hmac.new(SECRET.encode(), f"{t}.".encode() + body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, given)

@app.post("/hooks/offendersearch")
async def hook(req: Request):
    raw = await req.body()                                # the exact bytes; never re-serialise JSON first
    if not verify(req.headers.get("X-Offendersearch-Signature", ""), raw):
        raise HTTPException(400, "bad signature")
    event = json.loads(raw)                               # {"type": "monitor.alert", "event": "new", "alertId": …}
    # de-duplicate on event["alertId"], then hand off to a queue and answer fast
    return {"ok": True}

Paste a header you received into the webhook tester to check it in the browser; webhook example has the FastAPI receiver with retries and de-duplication, API signature a known-answer test vector, and the Monitoring API the create and rotate calls.

07

Async background checks in Python with httpx

Bounded concurrency for a queue of people, without tripping the limits.

requests is synchronous, which is fine for a form submission and slow for a queue. For a worker that screens many people, httpx.AsyncClient with an asyncio.Semaphore gives you a small pool of in-flight calls: three or four is a sensible start, because production rate limiting is a capacity signal rather than a per-key quota and a burst of a thousand coroutines is exactly how to meet it. The sandbox adds a second ceiling of 120 requests a minute per IP address, shared by every test key behind the same egress, so a CI runner on a shared NAT should keep the pool small too.

If nobody is waiting on the answer, there is a better shape than concurrency: POST /v1/searches accepts the same body, returns a searchId at once, and lets you poll GET /v1/searches/{searchId} or receive a callback, which is the pattern webhooks vs API polling compares. Monitors, covered in the previous section, replace polling altogether once the first check is done.

import asyncio, httpx

async def screen(people, concurrency=3):
    sem = asyncio.Semaphore(concurrency)                 # a small pool, not a burst
    async with httpx.AsyncClient(base_url=BASE, headers=HEADERS, timeout=45) as client:
        async def one(person):
            async with sem:
                r = await client.post("/v1/search", json={"query": person})
                r.raise_for_status()
                data = r.json()
                return person["lastName"], data["status"], data["counts"]["records"]
        return await asyncio.gather(*(one(p) for p in people))

rows = asyncio.run(screen([
    {"firstName": "Clear", "lastName": "Visitor"},
    {"firstName": "Exact", "lastName": "Match", "dob": "1980-01-01"},
]))
print(rows)       # [('Visitor', 'complete', 0), ('Match', 'complete', 1)]
08

FCRA or not: which Python integration you are building

A public-records lookup and a consumer report are two different endpoints and two different prices.

Path 1

Data API, not FCRA

$0.15a call, 25 free, no card
  • For: visitor and volunteer screening, trust and safety, research, monitoring, and software that shows a public record to the person who asked for it.
  • Must not decide: whether someone is hired, housed, insured or given credit. The response is a public-records lookup, not a consumer report, and the key is not approved for those uses.
  • Example: An admissions desk screens a visitor against the registries before a visit; no hiring, housing or credit decision is involved.

Self-serve: get a key, then POST /v1/search or /v1/criminal/search.

Path 2

FCRA Partner Access

$4.95per order, searches and live checks included, no court fees
  • Built in: end-user registration with a permissible purpose, consent on every order, the pre-adverse and adverse-action notices with the consumer’s copy, and a consumer portal.
  • Disputes: a dispute endpoint; the record is re-checked with the registry or court that holds it, with an outcome inside 30 days, and a correction reaches every partner that received it.
  • Example: A screening company furnishes a report an employer or landlord will act on; the order runs the consent, notice and dispute steps.

Under a written agreement: Request FCRA Partner Access.

The records can be the same; the process around them is not. How the program works: FCRA Partner Access · the orders endpoint: FCRA orders API · reference and statute citations: FCRA docs. This page describes the product, not legal advice.

09

What the background check API costs from Python

Per call, from the same constants the pricing page renders.

ItemPriceUnit
Registry or criminal search from Python$0.15per call, the first 2,000 in a calendar month
Volume rate$0.11per call past 2,000 in a calendar month
Free to start25 callsonce per account, on production data, no card
Sandbox$060 calls a minute and 2,000 a day per test key
Live re-verification+$0.02per completed live source, $2.00 ceiling per search; a source that did not answer is not billed

No minimum on search. The Map API has its own $300 monthly minimum. No seats, no platform fee, no per-state fee; a batch row is billed as one call.

Worked examples by volume: background check API pricing · every rate: pricing.

10

Limits and what the API does not return

Rate limits, the response cap, the 429 body and the records that are out of scope.

LimitValue
Sandbox, per test key60 calls a minute, 2,000 a day; nothing billed
Production, per keyNo published ceiling. A 429 only when the service is at capacity, with Retry-After; a 429 is never billed
Records per responseUp to 4,000 in one answer; above that capped: true, and perPage pages through the rest
Batch1,000 rows a call; a failing row is reported in place and never stops the batch
DeadlinedeadlineMs bounds the wait for slow jurisdictions; an unanswered one is named in sourceStatus and the answer says partial
EndpointsPOST /v1/search and /v1/criminal/search; one X-API-Key header
  • No civil cases, no traffic citations. Criminal records only: jail bookings, prison custody, court cases with dispositions, warrants, and the registries.
  • No international records. US county, state and federal sources, and the 58 US registries.
  • Not a consumer report. A hiring, housing, credit or insurance decision runs as an order through FCRA Partner Access, not through the standard key.
  • No SSN, no credit, no verifications, no drug or driving records. Scope comes from the name, the date of birth and the places you already hold.
  • No Python-specific quota. Limits are per key and per IP address, whatever the client library.

Retry rules and backoff: rate limits, retries and idempotency · every status code: errors.

What a rate-limit answer looks like
HTTP/1.1 429 Too Many Requests
Retry-After: 12
Content-Type: application/json

{
  "detail": {
    "code": "overloaded",
    "retryAfterSeconds": 12
  }
}
Nothing was searched and nothing was billed; wait retryAfterSeconds and send the same request again.
11

The offendersearch Python package, when it ships

A typed client with one method per endpoint. Until it publishes, the requests code above is the integration.

The offendersearch package is written and tested in the repository (packages/sdk-python) and publishes to PyPI with the first registry release; until then pip install offendersearch does not resolve, and this page deliberately teaches the REST calls first. The package wraps exactly those calls: client.search() is POST /v1/search, client.criminal.search_pages() is the paging generator above, client.batch() posts to /v1/batch, client.search_async() and client.wait() cover the async endpoint, client.monitors.create() returns the monitor with its secret, and offendersearch.webhooks.verify() is the HMAC check from hooks.py. It uses the standard library for HTTP, so it has no dependencies of its own, retries 429, 502, 503 and 504 while waiting Retry-After, and raises typed exceptions with the status, the API’s code and the message.

Release status, the Node client and the CLI are tracked on the SDK page. The same guide in JavaScript is background check API Node.js; the endpoint pages behind both are the background check API, the sex offender API and the free background check API page, which explains the 25 free calls and the sandbox. A Postman collection and the MCP server cover the no-code and agent paths.

# pip install requests               # everything above runs on this alone
# pip install offendersearch         # the typed client: publishes to PyPI with the first registry release;
#                                    # until then the install line does not resolve and the REST code above is the integration

from offendersearch import OffenderSearch, webhooks

client = OffenderSearch()                                     # reads OFFENDERSEARCH_API_KEY; os_test_ → sandbox
r = client.search({"firstName": "Exact", "lastName": "Match", "dob": "1980-01-01"})
for page in client.criminal.search_pages({"lastName": "Record"}, per_page=100): ...
out = client.batch([{"firstName": "Clear", "lastName": "Visitor"}], match="balanced")
job = client.search_async({"firstName": "Clear", "lastName": "Visitor"}); client.wait(job["searchId"])
m = client.monitors.create(product="criminal", type="person", person={"firstName": "Felony", "lastName": "Record", "dob": "1975-06-15"},
                           channels={"webhookUrl": "https://example.com/hooks/offendersearch"})
webhooks.verify(m["channels"]["webhookSecret"], header, raw_body)   # the same HMAC check as hooks.py
  • Python 3.9 or newer; py.typed ships in the package, so the TypedDicts above come for free.
  • An os_test_ key routes the client to the sandbox automatically; an os_live_ key to production.
  • Source is published with the first release; until then the examples on this page are the reference implementation.
FAQ

Background check API Python questions

What timeout should I set on requests for a background check call?

Forty-five seconds covers a synchronous search: a healthy one answers in well under a second, and the server keeps working past its own deadlineMs target up to the gateway’s ~40 s so that you receive a complete answer rather than a partial one. Pass timeout=(5, 45) to separate the connect and read limits, and use POST /v1/searches for anything a person is not waiting on.

Is it safe to retry a POST /v1/search from Python?

Yes. A search has no side effects beyond billing, and a 429, 502, 503 or 504 means it did not run and was not billed, so resending the same body is correct. Do not retry 400, 401, 402 or 422; those answer the same way every time. FCRA orders are the exception: send an Idempotency-Key so a retried POST returns the original order.

Should I use TypedDict, dataclasses or pydantic for the response?

TypedDict when you only want editor completion and mypy; it adds no runtime cost and the dicts stay dicts. pydantic when you want the response validated as it arrives, for example in a FastAPI service. A dataclass sits between the two but needs a conversion step for nested objects such as addresses and offenses. The field list on this page works for all three.

Does the API work with asyncio, httpx or aiohttp?

It is plain HTTPS and JSON, so any client works; the httpx example above is the shape to copy. Keep concurrency small with a semaphore. Celery or RQ workers calling requests synchronously are equally fine, and a batch call is usually simpler than either when the people are already in a list.

My sandbox calls hit 429 before 60 a minute. Why?

The sandbox also limits each IP address to 120 requests a minute, shared across every test key behind that address. A CI runner, a corporate proxy or a cloud NAT gateway can pool many callers onto one IP. Lower the pool size, honour Retry-After, and remember an account holds at most 3 active test keys.

How do I run this in pytest or CI without being billed?

Mint a test key in the dashboard and put it in OFFENDERSEARCH_TEST_KEY. Every call with an os_test_ key goes to the sandbox, which answers from fixed test people with production-shaped responses and bills nothing; test a background check integration shows a fixture per outcome.

Run the first Python background check from your terminal

Create a test key, export it, and paste first_check.py. The sandbox answers every time and bills nothing; 25 production calls are free when you are ready.