This tutorial uses the id-document-ocr API. See the docs, live demo, and pricing.
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 from phone photos of both sides of an ID card, 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). To reproduce phone conditions, we placed the specimen on a desk scene at 4032 x 3024 pixels, tilted it, and made one shot with a glare spot and one out of focus.
What a Phone Sends You
A phone photo is about 3 MB. We sent the front and back straight from the camera, 3.1 and 3.2 MB, and got this back:
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. An ID card does not need 12 megapixels. Resized to 1600 pixels on the long side, the same two photos weigh 0.46 and 0.50 MB, and every field is still read. At that size, four photos fit in one call.
HEIC and PDF files are different: they are already compressed, and the API accepts them as they are. Our two HEIC shots at full resolution were 1.9 MB each.
The Script
Save this as id_from_phone.py. shrink makes each photo upright and small, parse sends everything in one call, and next_step turns the result into a message for the person holding the card. Set RAPIDAPI_KEY in your environment 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 matters more than it looks: phones often save the pixels sideways and store the rotation in a tag. Rotating before resizing means the API always gets an upright card.
Step 1: One Side Is Not Enough
The user sends the front only:
$ 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 sideThe front was read cleanly and the API says ok for what it saw. Every value is visual_only, though: read from the printed text, with nothing to confirm it. On this card the machine-readable zone (MRZ) is on the back, with a check digit for the number and each date. next_step asks for the other side because sides is 1 and no MRZ was found.
Step 2: Front and Back, Any Order
The user adds the back. Your app does not need to know which photo is which:
$ 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 readsides=2 confirms that a front and a back were identified. Each field now reads mrz_confirmed: the printed value and the MRZ value agree, and the MRZ passed its check digits. That is the status to wait for before you trust a value automatically.
Step 3: Extra Shots Are Welcome
Users often take a second photo when the first looks bad, and send both. Here, 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 readSame result as two clean photos. The API groups the photos by side and votes field by field between duplicates, and a value confirmed by a check digit can never be outvoted by a blurry read. Your app can let users add photos freely instead of forcing exactly two. Each photo counts as one image toward your plan's quota, so stop at four.
Step 4: Ask for a Retake
Now a front with glare over the document number and a back out of focus. The MRZ cannot be read, and the number is not readable on the front either:
$ 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 reports it in missing_critical_fields and the verdict is review. next_step turns that into a message the user can act on. When the new photos arrive, send only the new set rather than adding them to the bad ones: the result above, with two fresh photos, is ok again.
HEIC From an iPhone, PDF From a Scanner
Both go through the same function. Two HEIC photos at full resolution:
$ 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 readA two page PDF, front on page 1 and back on page 2:
$ 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 readEach PDF page counts as one image, so this call reported meta.images: 2, exactly like two photos. Up to 6 images or pages go in one call.
Production Tips
- Guide the capture. A frame on the camera screen and a short hint ("lay the card flat, away from the window") cut retakes more than any code. The flow above handles the rest.
- Shrink on the device when you can. Resizing in the app before upload saves the user's data plan and your bandwidth. The same 1600 pixel rule applies.
- Wait for mrz_confirmed on cards with an MRZ.
visual_onlyvalues are useful to pre-fill a form, not to approve an account on their own. - One document per call. If a user sends a passport and an ID card together, the API flags
multiple_documentsandnext_stepasks for one at a time. - Do not keep the photos. Store the fields and the verdict, then delete the images. The ID Document OCR API does not store the images you send.
Next Step
Get a key on the ID Document OCR API page, save id_from_phone.py and run it on two photos of the specimen below, taken with your own phone. To understand the check digits behind mrz_confirmed, read our passport MRZ tutorial. To catch edited documents, see the fake ID detection tutorial, and to check that the person holding the card is the person in the photo, the selfie to ID verification guide.
Sources
- French ID card specimen, 2021 design, on Wikimedia Commons: front, back
- ICAO Doc 9303, Machine Readable Travel Documents
Frequently Asked Questions
- How do I read the front and back of an ID card in one API call?
- Send both photos in the same request to the ID Document OCR API, in any order, by repeating the images field. The API recognises which photo shows which side, reads both, and returns one set of fields. result.sides is 2 when it identified a front and a back, and fields read on both sides come back as mrz_confirmed.
- Why does my ID upload fail with Request Too Long?
- Phone photos are large. Two 12 megapixel JPEGs of 3.1 and 3.2 MB went over the request size limit in our test and the call returned 413 Request Too Long. Shrink each photo to about 1600 pixels on the long side before sending: the same two photos dropped to 0.46 and 0.50 MB and were read in full.
- Can I send HEIC photos from an iPhone or a scanned PDF?
- Yes. HEIC files and PDFs are accepted as they are, up to 4 MB per file. Each PDF page counts as one image, and a two page scan with the front on page 1 and the back on page 2 returns the same result as two photos. Up to 6 images or pages go in one call.
- What should I do when an ID photo is blurry or has glare?
- Read verdict.missing_critical_fields and verdict.consistency_issues. When a critical field such as document_number is missing, or unread_field is present, ask the user for new photos of both sides and send only the new set. Sending several shots of the same side also helps: the API votes field by field and a checksum-confirmed value always wins over a blurry read.



