This tutorial uses the id-document-ocr API. See the docs, live demo, and pricing.
A car rental desk, a van sharing app, a delivery platform signing up couriers: all of them need the same thing from a driving licence. Who is the driver, how old are they, can they drive this vehicle, and is the licence still valid when the car comes back. This tutorial reads EU driving licences 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, which reads ID cards, passports, residence permits and driving licences. Every result below is a live call on official specimen licences from six countries.
One Layout for Every EU Licence
Under the EU directive on driving licences, every member state, plus Norway, Iceland and Liechtenstein, prints the same numbered fields on the same credit card format. The language changes, the numbers do not:
| Field | Content | API key |
|---|---|---|
| 1 and 2 | Surname, first names | last_name, first_name |
| 3 | Date and place of birth | birth_date |
| 4a and 4b | Issue date, expiry date | issue_date, expiry_date |
| 4c and 4d | Issuing authority, personal number (some countries) | authority, personal_number |
| 5 | Licence number | document_number |
| 9 | Vehicle categories | license_categories |

One thing a licence does not have is a machine-readable zone. Passports and most ID cards carry MRZ lines with check digits, which our passport MRZ tutorial uses to prove each field. On a licence, the fields come from the printed card, with the status visual_only. The checks that make a licence safe to accept are rules about dates and categories, and they belong in your code. That is what the script adds.
The Script
parse_licence calls the API, categories turns field 9 into a set of codes, and check_rental decides. Set your key in the RAPIDAPI_KEY environment variable and install requests.
import os
import re
from datetime import date
import requests
KEY = os.environ["RAPIDAPI_KEY"]
HOST = "id-document-ocr-verification.p.rapidapi.com"
# EU categories, longest first so "C1E" is not read as "C" + "1E"
CODES = ["C1E", "D1E", "AM", "A1", "A2", "B1", "BE", "C1", "CE", "D1", "DE",
"A", "B", "C", "D", "T"]
# a higher category includes lower ones: BE needs B, C1E needs C1
INCLUDES = {"A": "A2", "A2": "A1", "A1": "AM", "B": "AM", "BE": "B",
"C1": "B", "C": "C1", "C1E": "C1", "CE": "C", "D1": "B", "D": "D1",
"D1E": "D1", "DE": "D"}
def parse_licence(*paths):
"""Send one or both sides of a licence, return the API result."""
files = [("images", open(p, "rb")) for p in paths]
r = requests.post(f"https://{HOST}/parse-id",
headers={"x-rapidapi-key": KEY, "x-rapidapi-host": HOST},
files=files, timeout=60)
r.raise_for_status()
return r.json()["result"]
def categories(raw):
"""Field 9 as a set of codes: 'AM / B', 'A BE C1E', 'ABC' all work."""
found = set()
for token in re.split(r"[s/,;]+", (raw or "").upper()):
while token:
code = next((c for c in CODES if token.startswith(c)), None)
if code is None:
break
found.add(code)
token = token[len(code):]
for code in list(found):
while code in INCLUDES:
code = INCLUDES[code]
found.add(code)
return found
def age_on(birth, day):
return day.year - birth.year - ((day.month, day.day) < (birth.month, birth.day))
def value(result, name):
v = result["fields"].get(name, {}).get("value")
return date.fromisoformat(v) if v and name.endswith("_date") else v
def check_rental(result, return_day, today=None, min_age=21, need="B"):
"""Return (decision, reasons) for one rental: ok, review or deny."""
today = today or date.today()
if result["document_type"] != "driving_license":
return "review", ["not a driving licence"]
birth, issued = value(result, "birth_date"), value(result, "issue_date")
expiry = value(result, "expiry_date")
held = categories(value(result, "license_categories"))
deny, review = [], []
if birth is None:
review.append("no birth date")
elif age_on(birth, today) < min_age:
deny.append(f"driver is {age_on(birth, today)}, minimum {min_age}")
if not held:
review.append("categories not read")
elif need not in held:
deny.append(f"category {need} missing (has {', '.join(sorted(held))})")
if expiry is None:
review.append("no expiry date printed (pre-2013 card?)")
elif expiry < today:
deny.append(f"expired {expiry}")
elif expiry < return_day:
deny.append(f"expires {expiry}, before the car is back")
if birth and issued and age_on(birth, issued) < 17:
review.append(f"issued at age {age_on(birth, issued)}")
if issued and issued > today:
review.append("issue date in the future")
if issued and expiry and (expiry - issued).days > 15 * 366:
review.append("valid for more than 15 years")
if deny:
return "deny", deny
if review:
return "review", review
return "ok", [f"age {age_on(birth, today)}, {need} held, valid to {expiry}"]
if __name__ == "__main__":
import sys
return_day = date.fromisoformat(sys.argv[1])
result = parse_licence(*sys.argv[2:])
decision, reasons = check_rental(result, return_day)
print(f"{decision:7}", "; ".join(reasons))The default rule is a rental car: driver 21 or older, category B, licence valid until the return date. Every condition that cannot be decided from the card, such as a missing expiry date, goes to review instead of deny, so a person looks before you turn a customer away.
Step 1: Read the Licence
/parse-id takes one or several images in the images field: the front alone, or front and back together in one call. On the Polish specimen:
lic = parse_licence("poland.png")
for k in ["last_name", "first_name", "birth_date", "issue_date",
"expiry_date", "license_categories"]:
print(f"{k:19} {lic['fields'][k]['value']:12} {lic['fields'][k]['status']}")last_name KOWALSKI visual_only
first_name JAN visual_only
birth_date 1964-04-07 visual_only
issue_date 2019-03-06 visual_only
expiry_date 2028-01-18 visual_only
license_categories A / B visual_onlyDates come back in ISO format whatever the country prints, 07.04.1964 in Poland or 01/01/65 in Italy, so date.fromisoformat reads them directly. document_type is driving_license, which is the first thing check_rental tests: a customer who uploads an ID card by mistake gets review, not a rental.
Step 2: Turn Field 9 into Categories
Field 9 is printed differently in every country: A/B in Poland, AM, A, B in Greece, ABC with no spaces in Finland, codes in boxes in Germany. categories splits the text and reads the longest code first, so C1E is one category and not C followed by noise. Anything that is not a category code is ignored.
Then it adds the categories a licence includes without printing them. Holding BE means holding B, C1 requires B, and A covers A2, A1 and AM. Without this step, a driver with only BE C1E printed would fail a check for B. A van over 3.5 tonnes needs C1, so the same function decides a van rental:
back = date(2026, 12, 5)
for paths in [("norway_front.jpg", "norway_back.png"), ("poland.png",)]:
lic = parse_licence(*paths)
print(paths[0], check_rental(lic, back, need="C1"))norway_front.jpg ('ok', ['age 54, C1 held, valid to 2033-09-01'])
poland.png ('deny', ['category C1 missing (has A, A1, A2, AM, B)'])Step 3: Decide, on Six Countries
We ran the script on specimen licences for a car returned on December 5, 2026:
$ python licence_check.py 2026-12-05 poland.png
ok age 62, B held, valid to 2028-01-18
$ python licence_check.py 2026-12-05 greece.jpg
ok age 51, B held, valid to 2029-02-18
$ python licence_check.py 2026-12-05 norway_front.jpg norway_back.png
ok age 54, B held, valid to 2033-09-01
$ python licence_check.py 2026-12-05 germany_2013.jpg
ok age 62, B held, valid to 2030-01-21
$ python licence_check.py 2026-12-05 italy.jpg
deny expired 2025-01-01
$ python licence_check.py 2026-12-05 germany_1999.jpg
review no expiry date printed (pre-2013 card?)
$ python licence_check.py 2026-12-05 romania.jpg
deny expired 2018-06-10Four licences pass. The Italian and Romanian specimens are expired, which is a plain deny. The last check, the expiry against the return date, matters on long rentals: the same Polish licence for a car returned on February 1, 2028 gives:
$ python licence_check.py 2028-02-01 poland.png
deny expires 2028-01-18, before the car is backLicences with No Expiry Date
The 1999 German specimen has a dash in field 4b. That is not a reading problem: German licences issued before 19 January 2013 were valid for life, and several countries had similar rules. EU law now requires every licence issued before that date to be replaced by 19 January 2033, so these cards are still valid today and you will meet them at the rental desk.
check_rental sends them to review rather than deny. If your business accepts them, replace the review with a rule: country is Germany, issue date before 2013, no expiry, then ok until 2033. Field 4a also tells you something here: it is the date this card was issued, not the date the driver passed the test. A driver who renewed last year has a recent 4a and twenty years of experience.
Romanian Licences: the Personal Number Checks Itself
Some countries print a national personal number in field 4d. Romania prints the CNP, a 13-digit number that encodes the sex and birth date and ends with a check digit. The API verifies it and reports the result in verdict.national_checks:
>>> lic = parse_licence("romania.jpg")
>>> lic["verdict"]["national_checks"]
{'rou_cnp': True}
>>> lic["fields"]["birth_date"]
{'value': '1989-03-06', 'status': 'derived_from_document_number'}On this licence the birth date has the status derived_from_document_number: it comes from a number whose checksum passed, which the documentation ranks as high trust. For a Romanian driver, the age in check_rental rests on a verified number, not only on printed text.
For Driver Platforms: Check Again Before It Expires
A rental checks a licence once. A delivery or ride-hailing platform keeps the driver for years, and a licence that was valid at signup expires later. Store the expiry date with the driver and ask for a new photo before it runs out:
from datetime import timedelta
def recheck_on(result, days_before=30):
expiry = value(result, "expiry_date")
return expiry - timedelta(days=days_before) if expiry else Nonegreece.jpg 2029-01-19
germany_2013.jpg 2029-12-22A driver with no expiry date returns None: put them on a fixed schedule, for example once a year, until the 2033 replacement. For the identity side of signup, our eKYC tutorial compares the selfie with the photo on the document.
Production Tips
- Ask for both sides. The back lists every category with the date it was first obtained (column 10). That is the date to use for rules like "licence held for two years", since 4a on the front changes at every renewal. The API accepts front and back in one call.
- Keep the rules in config. Minimum age, young driver surcharge, required category and accepted countries change by market and by vehicle. Pass them to
check_rentalinstead of editing the code. - Show the customer a short message. "We could not confirm your licence, an agent will check it" is enough. Keep the detailed reason for your staff.
- Store the decision, not the image. Keep the decision, the reasons, the expiry date and the licence number if your contract needs it, then delete the photos. The ID Document OCR API does not store the images you send.
- Ask for a better photo first. When a field comes back missing, a second photo, flat and without glare, usually fixes it. Several photos of the same side can go in one call, and the API votes field by field.
Next Step
Get a key on the ID Document OCR API page, save licence_check.py, and run it on a specimen licence from the sources below. Then set min_age and need to your own rules. For guests rather than drivers, see our guest ID verification guide, and for edited documents, the fake ID detection tutorial.
Sources
- Directive 2006/126/EC on driving licences (EUR-Lex)
- Specimen licences on Wikimedia Commons, public domain unless noted: Poland, Greece, Norway front, Norway back, Germany 2013, Germany 1999, Italy (CC0), Romania
Frequently Asked Questions
- Can an API read a driving licence?
- Yes. The ID Document OCR API reads EU-format driving licences and returns the holder's names, birth date, issue and expiry dates, issuing authority and categories as JSON, with document_type set to driving_license. In our tests it read specimen licences from Poland, Greece, Norway, Germany, Italy and Romania. Send both sides in one call when you have them.
- What do the numbers on an EU driving licence mean?
- Every licence issued on the EU model uses the same numbered fields: 1 surname, 2 first names, 3 date and place of birth, 4a issue date, 4b expiry date, 4c issuing authority, 4d an optional personal number, 5 licence number, 7 signature and 9 categories. The back repeats the categories in a table with the date each one was first obtained.
- How do I check that a driver can rent a car?
- Read the licence, then check four things in code: the driver's age against your minimum, category B in field 9, an expiry date after the day the car comes back, and dates that make sense together. The check_rental function in this tutorial does all four and returns ok, review or deny with the reasons.
- Why does a German licence have no expiry date?
- German licences issued before 19 January 2013 were valid for life, so field 4b is empty or shows a dash. EU rules require all licences issued before that date to be replaced by 19 January 2033. Until then such a card is valid, so the safest automated answer is review rather than deny.



