A rental counter, a car sharing app, a peer-to-peer rental platform: before the keys change hands, someone has to read the driver's license and decide. Is the driver old enough, does the class allow a car, and will the license still be valid on the day the car comes back? This tutorial reads US driver's licenses with an API in Python and turns those questions into one function that returns ok, review or deny.
It uses the ID Document OCR API. Every output below comes from live calls made on 29 November 2026 on three state sample licenses: California (2025 design), Massachusetts (2016) and Washington D.C. (2018).
One numbering for every state
Each state designs its own card, but licenses that follow the AAMVA card design standard number their fields the same way, and the numbers are the ones used on European licenses:
-
1 and 2: family name and given names (
last_name,first_name) -
3: date of birth (
birth_date) -
4a and 4b: issue and expiration dates (
issue_date,expiry_date) -
4d: license number (
document_number) -
9: class (
license_categories)
The license number is field 4d on a US card and field 5 on a European one. If you rent cars on both sides of the Atlantic, the EU driving licence tutorial covers categories and pre-2013 cards.
The script
Save this as us_license_check.py. Set your key in RAPIDAPI_KEY and install requests.
import os
from datetime import date
import requests
KEY = os.environ["RAPIDAPI_KEY"]
HOST = "id-document-ocr-verification.p.rapidapi.com"
def parse_license(path):
"""Send the front of a US driver's license, return the API result."""
with open(path, "rb") as f:
r = requests.post(f"https://{HOST}/parse-id",
headers={"x-rapidapi-key": KEY, "x-rapidapi-host": HOST},
files={"images": f}, timeout=60)
r.raise_for_status()
return r.json()["result"]
def value(result, name):
v = result["fields"].get(name, {}).get("value")
return date.fromisoformat(v) if v and name.endswith("_date") else v
def age_on(birth, day):
return day.year - birth.year - ((day.month, day.day) < (birth.month, birth.day))
def classes(raw):
"""'C', 'D', 'DM' or 'A, M' as a set of single-letter classes."""
return {c for c in (raw or "").upper() if c.isalpha()}
def check_rental(result, return_day, today=None, min_age=21, young_until=25):
"""Return (decision, notes) for one car rental: ok, review or deny."""
today = today or date.today()
if result["document_type"] != "driving_license":
return "review", ["not a driver's license"]
if result.get("country") != "USA":
return "review", [f"issued in {result.get('country')}, use the EU rules"]
birth, issued = value(result, "birth_date"), value(result, "issue_date")
expiry = value(result, "expiry_date")
held = classes(value(result, "license_categories"))
checks = result["verdict"].get("national_checks", {})
deny, review, notes = [], [], []
if birth is None:
review.append("no date of birth")
else:
age = age_on(birth, today)
if age < min_age:
deny.append(f"driver is {age}, minimum {min_age}")
elif age < young_until:
notes.append(f"driver is {age}: young renter fee")
if not held:
review.append("license class not read")
elif held == {"M"}:
deny.append("motorcycle-only license (class M)")
if expiry is None:
review.append("no expiration date")
elif expiry < today:
deny.append(f"expired {expiry}")
elif expiry < return_day:
deny.append(f"expires {expiry}, before the car is back")
if checks.get("document_number_format") is False:
review.append("license number does not match the state format")
if birth and issued and age_on(birth, issued) < 16:
review.append(f"issued at age {age_on(birth, issued)}")
if issued and expiry and (expiry - issued).days > 12 * 366:
review.append("valid for more than 12 years")
if deny:
return "deny", deny
if review:
return "review", review
return "ok", notes or [f"class {', '.join(sorted(held))}, valid to {expiry}"]
if __name__ == "__main__":
import sys
return_day = date.fromisoformat(sys.argv[1])
for path in sys.argv[2:]:
decision, notes = check_rental(parse_license(path), return_day)
print(f"{os.path.basename(path):18} {decision:7}", "; ".join(notes))
Read the license
One call with the photo of the front returns every printed field. On the 2025 California sample, in 1.7 seconds:
result = parse_license("california.jpg")
for name, field in result["fields"].items():
if field["value"] is not None:
print(f"{name:20} {field['value']}")
print(result["verdict"]["national_checks"])
birth_date 1957-11-26
document_number I1234567
expiry_date 2030-11-26
first_name JANICE
issue_date 2025-11-09
last_name SAMPLE
license_categories A
sex F
{'document_number_format': True}
document_number_format: True means the number matches the format California uses, one letter then seven digits. It is the check that catches an I read as a 1, the most common confusion on these cards.
The rental rules
-
Age: under
min_age(21 by default) is a deny; underyoung_until(25) the rental is allowed with a young renter fee note. -
Class: letters change from state to state, so only a motorcycle-only license (
Malone) is denied. - Expiration: the license must be valid until the return day, not only today.
- Review: a number that fails the state format check, a missing field, an issue date before age 16 or a validity over 12 years go to a person.
verdict.status tells you the document was read cleanly. Expiration is a separate fact (verdict.is_expired, expiry_date), so the script compares the date with the return day itself.
Run it on three states
A rental from 29 November to 3 December 2026, then the California license on a rental that ends after its expiration date:
$ python us_license_check.py 2026-12-03 california.jpg massachusetts.jpg dc.png
california.jpg ok class A, valid to 2030-11-26
massachusetts.jpg deny expired 2021-01-12
dc.png deny expired 2018-02-21
$ python us_license_check.py 2030-12-01 california.jpg
california.jpg deny expires 2030-11-26, before the car is back
Production tips
- Ask for a flat photo without glare: several photos of the same side can go in one call.
- Keep the rules in config: minimum age and young renter threshold change by company and state.
- Route foreign licenses to the EU rules instead of refusing them.
- Store the decision, not the image: the ID Document OCR API does not store the images you send.
Full tutorial with the field map and sources: US Driver's License OCR in Python on ai-engine.net.
Next step
Get a key on the ID Document OCR API page, save
us_license_check.pyand run it on a sample license. Then setmin_ageandyoung_untilto your own policy.

Top comments (0)