Production-Ready Driver's License OCR for Go
Extract and validate driver's license data in seconds via a direct HTTP POST request.
Why Driver's License OCR is Difficult
Parsing driver's licenses presents significant engineering challenges beyond simple OCR. Physical documents are susceptible to glare, shadows, and low-light conditions, degrading image quality. Skew and rotation from mobile captures require robust preprocessing. Generic OCR engines like Tesseract fail on the specialized fonts and layouts found on IDs. Furthermore, extracting structured data requires parsing complex formats like the PDF417 barcode, which contains AAMVA-encoded data that must be correctly decoded and validated. Manually maintaining regex patterns for dozens of jurisdictional layouts is brittle and resource-intensive, leading to high error rates and ongoing maintenance overhead.
Enterprise-Grade Extraction with StructOCR
StructOCR bypasses the fragility of open-source tools. Our driver license verification api is powered by pre-trained deep learning models specifically tuned for identity documents from 200+ jurisdictions, including various forms of driving permits. The service performs automatic image pre-processing, including deskewing, denoising, and glare removal, before extraction. Unlike Tesseract, which returns unstructured text lines, StructOCR delivers a standardized, validated JSON object with discrete fields like `date_of_birth` and `document_number`. This eliminates the need for post-processing and ensures consistent, reliable data integration. To check the output on your own sample first, upload a photo to the free online driver license scanner.
Production Use Cases
- Digital Onboarding (KYC): Reduce drop-off rates by pre-filling user data from Driver's Licenses in < 2 seconds.
- Fraud Prevention: Detect tampered fonts or mismatched MRZ checksums automatically.
- Global Compliance: Handle Driver's Licenses from 200+ jurisdictions without custom rules.
Implementation: Go (Golang)
The following Go code provides a robust implementation. It handles file reading, Base64 encoding, header authentication using 'x-api-key', and structured JSON parsing into native Go structs.
Prerequisite: Go 1.16+
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
// Get 200 free credits:
// 👉 https://structocr.com/register
// RequestPayload defines the structure for the API request body.
type RequestPayload struct {
Image string `json:"img"`
}
// ExtraDetailsData handles regional specifics and deep security codes.
type ExtraDetailsData struct {
CardSecurityNumber *string `json:"card_security_number"`
FathersName *string `json:"fathers_name"`
MothersName *string `json:"mothers_name"`
RgNumber *string `json:"rg_number"`
}
// DriverLicenseData defines the structure of the extracted data.
type DriverLicenseData struct {
Type string `json:"type"`
CountryCode string `json:"country_code"`
Region string `json:"region"`
DocumentNumber string `json:"document_number"`
PersonalNumber *string `json:"personal_number"`
Surname string `json:"surname"`
GivenNames string `json:"given_names"`
DateOfBirth string `json:"date_of_birth"`
DateOfExpiry string `json:"date_of_expiry"`
DateOfIssue string `json:"date_of_issue"`
Sex string `json:"sex"`
Address string `json:"address"`
VehicleClass string `json:"vehicle_class"`
ExtraDetails *ExtraDetailsData `json:"extra_details"`
}
// APIResponse defines the structure of the full API response.
type APIResponse struct {
Success bool `json:"success"`
Data DriverLicenseData `json:"data"`
Error string `json:"error,omitempty"` // Capture error codes if any
}
func main() {
// 1. Setup Configuration
apiURL := "https://api.structocr.com/v1/driver-license"
apiKey := "YOUR_API_KEY_HERE" // Replace with your actual key
imagePath := "license.jpg" // Ensure this file exists
// 2. Read Image and Encode to Base64
imageBytes, err := os.ReadFile(imagePath)
if err != nil {
fmt.Printf("Error reading image: %v\n", err)
return
}
base64Image := base64.StdEncoding.EncodeToString(imageBytes)
// 3. Prepare Request Payload
payload := RequestPayload{
Image: base64Image,
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
fmt.Printf("Error marshalling payload: %v\n", err)
return
}
// 4. Create HTTP Request
req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer(payloadBytes))
if err != nil {
fmt.Printf("Error creating request: %v\n", err)
return
}
// Important: Set the correct headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-api-key", apiKey)
// 5. Execute Request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Network error: %v\n", err)
return
}
defer resp.Body.Close()
// 6. Parse Response
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
fmt.Printf("API Error (%d): %s\n", resp.StatusCode, string(body))
return
}
var apiResponse APIResponse
if err := json.Unmarshal(body, &apiResponse); err != nil {
fmt.Printf("JSON Parse Error: %v\n", err)
return
}
if apiResponse.Success {
fmt.Println("✅ Extraction Successful!")
fmt.Printf("Type: %s\n", apiResponse.Data.Type)
fmt.Printf("Name: %s %s\n", apiResponse.Data.GivenNames, apiResponse.Data.Surname)
fmt.Printf("Doc Number: %s\n", apiResponse.Data.DocumentNumber)
fmt.Printf("Expiry: %s\n", apiResponse.Data.DateOfExpiry)
fmt.Printf("Vehicle Class: %s\n", apiResponse.Data.VehicleClass)
// Highlighting the advanced security feature extraction
if apiResponse.Data.ExtraDetails != nil && apiResponse.Data.ExtraDetails.CardSecurityNumber != nil {
fmt.Printf("Security Code (DD): %s\n", *apiResponse.Data.ExtraDetails.CardSecurityNumber)
}
} else {
fmt.Printf("API indicated failure: %s\n", apiResponse.Error)
}
}Technical Specs
- •Latency: < 4s (Average)
- •Availability: Served from Cloudflare's global edge network
- •Security: AES-256 Encryption & SOC2 Compliant
- •Input: JPG, PNG, WebP (Base64 Encoded)
- •Max File Size: 4.5MB
- •Output: JSON (Structured Data)
Key Features
- •True Global Compatibility: Out-of-the-box support for North American AAMVA standards, EU numbered fields, and complex LATAM layouts (e.g., Brazil CNH) without maintaining custom RegEx.
- •Date Normalization: Dates returned in YYYY-MM-DD format.
- •Vehicle Class Extraction: Parses complex vehicle categories (A, B, C, etc).
Sample JSON Output
StructOCR returns a normalized JSON object, regardless of the input image angle or quality.
{
"success": true,
"data": {
"type": "drivers_license",
"country_code": "USA",
"region": "CA",
"document_number": "E3802489",
"personal_number": null,
"surname": "IDNOOB",
"given_names": "MING",
"address": "750 GONZALEZ DR APT 6B, SAN FRANCISCO, CA 94512",
"vehicle_class": "C",
"sex": "F",
"date_of_birth": "1988-06-06",
"date_of_expiry": "2020-06-06",
"date_of_issue": "2015-07-22",
"extra_details": {
"card_security_number": "06/09/2014599A5/DOFD/19",
"fathers_name": null,
"mothers_name": null,
"rg_number": null
}
}
}Frequently Asked Questions
How does StructOCR compare to AWS Textract or Google Vision?
Unlike general-purpose OCR services like AWS Textract or Google Vision that return raw text blocks, StructOCR is a specialized API. It is purpose-built for identity documents, returning a structured JSON object with pre-defined, validated fields such as `surname`, `date_of_birth`, and `document_number`. This eliminates the need for complex post-processing and pattern matching on your end.
Do you store the uploaded images?
Only briefly. Uploaded images and results are kept for at most 24 hours for quality spot-checks, then deleted. We do not persist any of your customer's PII.
How to handle blurry images?
Our API includes an internal image enhancement engine that automatically attempts to deblur, denoise, and correct for poor lighting conditions before processing. For best results, we recommend a minimum resolution of 300 DPI.
You May Also Like
Related tutorials, platform guides, and comparisons
Java Driver License OCR API
Upload an image for a free test! High-accuracy Java Driver's License OCR API. Get structured JSON output from images via a simple HTTP request. Eliminate manual entry & Tesseract errors.
Canada Driver License OCR with Node.js SDK
Extract structured fields from a Canada provincial driver licence with the StructOCR Node.js SDK and TypeScript + Express.
Node.js Driver License Verification API
Stop manual driver license checks. Our Node.js API delivers verified data in JSON within <4s, secured by AES-256 encryption and SOC2 compliance. Upload an image for a free test!
UK Driver License OCR with Python SDK
Extract structured fields from a United Kingdom photocard driving licence with the StructOCR Python SDK and FastAPI.
UK Driver License OCR with Node.js SDK
Extract structured fields from a United Kingdom photocard driving licence with the StructOCR Node.js SDK and TypeScript + Express.
C# Driver's License OCR API
Upload an image for a free test! High-accuracy C# Driver's License OCR API. Get structured JSON output from images, parse PDF417 barcodes, and eliminate manual entry errors.
Philippines Driver License OCR with Python SDK
Extract structured fields from a Philippines LTO driver's license with the StructOCR Python SDK and FastAPI.
Brazil Driver License OCR with Node.js SDK
Extract structured fields from a Brazil Carteira Nacional de Habilitação (CNH) with the StructOCR Node.js SDK and TypeScript + Express.
Philippines Driver License OCR with Node.js SDK
Extract structured fields from a Philippines LTO driver's license with the StructOCR Node.js SDK and TypeScript + Express.
Canada Driver License OCR with Python SDK
Extract structured fields from a Canada provincial driver licence with the StructOCR Python SDK and FastAPI.
Java US Driver License PDF417 API Tutorial
Decode US driver license PDF417 barcodes with Java. Send a license-back image, parse AAMVA fields, and handle unreadable barcode errors safely.
Technical Comparisons & Integrations
Explore platform integrations and competitive analysis
Add Driver's License OCR to Your Bolt.new App in 5 Minutes
Step-by-step guide to integrating the StructOCR Driver's License scanner API into a Bolt.new app. Build car rental and mobility onboarding flows right in your browser.
Add Driver's License OCR using Cursor in 5 Minutes
Step-by-step guide to integrating the StructOCR Driver's License scanner API using the Cursor AI code editor. Build car rental and mobility onboarding flows rapidly.
Add Driver's License OCR to Your Lovable.dev App in 5 Minutes
Step-by-step guide to integrating the StructOCR Driver's License scanner API into a Lovable.dev app. Build car rental and mobility onboarding flows with zero backend.
Add Driver's License OCR to Your Replit App in 5 Minutes
Step-by-step guide to integrating the StructOCR Driver's License scanner API into a Replit application. Build car rental and mobility onboarding flows using Replit Agent and Secrets.
Add Driver's License OCR to Your v0 App in 5 Minutes
Step-by-step guide to integrating the StructOCR Driver's License scanner API into a v0 by Vercel app. Build car rental and mobility onboarding flows with zero backend.
Add Receipt OCR to Your Bolt.new App in 5 Minutes
Step-by-step guide to integrating the StructOCR receipt API into a Bolt.new app. Build expense tracking and receipt scanning tools right in your browser.
From tutorial to production in 5 minutes.
You've seen the code. Now get your API key, grab your 200 free credits, and see it work with your own images. No credit card required.