Your onboarding screen asks for a photo of an ID card. What arrives is two 12 megapixel JPEGs, maybe an HEIC from an iPhone, maybe a PDF from a scanner app, the back sometimes before the front, and one shot with a reflection right across the document number. This tutorial turns that into checked JSON in Python, and tells the user what to do next when a photo is not good enough.
It uses the ID Document OCR API. Every output below comes from live calls made on 1 December 2026 on the official French ID card specimen (2021 design), placed on a desk scene at 4032 x 3024 pixels, tilted, with one glare shot and one blurry shot.
What a phone sends you
We sent the front and back straight from the camera, 3.1 and 3.2 MB:
413 {'message': 'Request Too Long'}
The request body is limited to about 6 MB (around 4.5 MB of raw files once encoded), and each file to 4 MB. Resized to 1600 pixels on the long side, the same photos weigh 0.46 and 0.50 MB and every field is still read. HEIC and PDF files are already compressed and go as they are.
The script
Save this as id_from_phone.py. Set RAPIDAPI_KEY and install requests and pillow.
"""Read both sides of an ID card from phone photos and tell the user what to retake."""
import io
import os
import sys
import requests
from PIL import Image, ImageOps
URL = "https://id-document-ocr-verification.p.rapidapi.com/parse-id"
HEADERS = {
"x-rapidapi-key": os.environ["RAPIDAPI_KEY"],
"x-rapidapi-host": "id-document-ocr-verification.p.rapidapi.com",
}
MAX_SIDE = 1600 # pixels on the long side, plenty for an ID card
BODY_LIMIT = 4_500_000 # raw bytes per call, all files together
def shrink(path):
"""Phone photo -> upright JPEG under MAX_SIDE. PDF and HEIC go as they are."""
if path.lower().endswith((".pdf", ".heic", ".heif")):
return os.path.basename(path), open(path, "rb").read()
img = ImageOps.exif_transpose(Image.open(path)).convert("RGB")
img.thumbnail((MAX_SIDE, MAX_SIDE))
buf = io.BytesIO()
img.save(buf, "JPEG", quality=90)
return os.path.basename(path), buf.getvalue()
def parse(paths):
files = [shrink(p) for p in paths]
size = sum(len(data) for _, data in files)
if size > BODY_LIMIT:
raise ValueError(f"{size} bytes: send fewer photos or lower MAX_SIDE")
r = requests.post(URL, headers=HEADERS, timeout=60,
files=[("images", (name, data)) for name, data in files])
r.raise_for_status()
return r.json()["result"]
def next_step(result):
"""What to tell the person holding the card."""
verdict = result["verdict"]
issues = verdict["consistency_issues"]
missing = verdict["missing_critical_fields"]
if "multiple_documents" in issues:
return "retake", "these photos show two different documents, send one at a time"
if result["sides"] < 2 and not verdict["mrz_present"]:
return "retake", "now take a photo of the other side"
if "unread_field" in issues or missing:
what = ", ".join(missing) or "a field"
return "retake", f"{what} could not be read, retake both sides flat, sharp and without glare"
if verdict["status"] == "ok":
return "done", "thanks, your ID is read"
return "review", "a person will check this ID"
if __name__ == "__main__":
result = parse(sys.argv[1:])
action, message = next_step(result)
fields = {k: f["value"] for k, f in result["fields"].items() if f["value"]}
print(f"sides={result['sides']} verdict={result['verdict']['status']}")
for name in ("last_name", "document_number", "birth_date", "expiry_date"):
if name in fields:
status = result["fields"][name]["status"]
print(f" {name:16} {fields[name]:24} {status}")
print(f"{action}: {message}")
ImageOps.exif_transpose rotates the photo upright before resizing: phones often save the pixels sideways and store the rotation in a tag.
Step 1: one side is not enough
$ python id_from_phone.py front_1.jpg
sides=1 verdict=ok
last_name MARTIN visual_only
document_number X4RTBPFW4 visual_only
birth_date 1990-07-13 visual_only
expiry_date 2030-02-11 visual_only
retake: now take a photo of the other side
Every value is visual_only: read from the printed text, with nothing to confirm it. On this card the MRZ, with its check digits, is on the back, so next_step asks for the other side.
Step 2: front and back, any order
$ python id_from_phone.py back_1.jpg front_1.jpg
sides=2 verdict=ok
last_name MARTIN mrz_confirmed
document_number X4RTBPFW4 mrz_confirmed
birth_date 1990-07-13 mrz_confirmed
expiry_date 2030-02-11 mrz_confirmed
done: thanks, your ID is read
sides=2 confirms a front and a back. Each field is now mrz_confirmed: printed value and MRZ agree, and the check digits pass. That is the status to wait for before trusting a value automatically.
Step 3: extra shots are welcome
Four shots: the back, a front with a reflection, a clean front and a blurry back.
$ python id_from_phone.py back_1.jpg front_glare.jpg front_1.jpg back_blur.jpg
sides=2 verdict=ok
last_name MARTIN mrz_confirmed
document_number X4RTBPFW4 mrz_confirmed
birth_date 1990-07-13 mrz_confirmed
expiry_date 2030-02-11 mrz_confirmed
done: thanks, your ID is read
The API groups photos by side and votes field by field, and a value confirmed by a check digit can never be outvoted by a blurry read. Each photo counts as one image toward your quota, so stop at four.
Step 4: ask for a retake
A front with glare over the number and a back out of focus:
$ python id_from_phone.py front_glare2.jpg back_blur2.jpg
sides=2 verdict=review
last_name MARTIN visual_only
birth_date 1990-07-13 visual_only
expiry_date 2030-02-11 visual_only
retake: document_number could not be read, retake both sides flat, sharp and without glare
The API does not guess the number: it lists it in missing_critical_fields. When the new photos arrive, send only the new set, not the bad ones with them.
HEIC and PDF
$ python id_from_phone.py front_1.heic back_1.heic
sides=2 verdict=ok
last_name MARTIN mrz_confirmed
document_number X4RTBPFW4 mrz_confirmed
birth_date 1990-07-13 mrz_confirmed
expiry_date 2030-02-11 mrz_confirmed
done: thanks, your ID is read
$ python id_from_phone.py scan.pdf
sides=2 verdict=ok
last_name MARTIN mrz_confirmed
document_number X4RTBPFW4 mrz_confirmed
birth_date 1990-07-13 mrz_confirmed
expiry_date 2030-02-11 mrz_confirmed
done: thanks, your ID is read
Each PDF page counts as one image (meta.images: 2 here). Up to 6 images or pages per call.
Production tips
- Guide the capture: a frame on the camera screen and a hint to lay the card flat cut retakes more than any code.
- Shrink on the device to save the user's data plan; the same 1600 pixel rule applies.
- Wait for mrz_confirmed on cards with an MRZ before approving an account.
- Do not keep the photos: store the fields and verdict. The ID Document OCR API does not store the images you send.
Full tutorial with the retake flow image and sources: Read Both Sides of an ID Card From Phone Photos on ai-engine.net. For the check digits behind mrz_confirmed, see the passport MRZ tutorial.
Next step
Get a key on the ID Document OCR API page, save
id_from_phone.pyand run it on two photos of the French specimen taken with your own phone.

Top comments (0)