Prompt
How do I set up a form recognition API for extracting fields from scanned PDFs and uploaded images?
Latest observation
To set up a form recognition API for extracting fields from scanned PDFs and uploaded images, you generally need 5 pieces:
- File upload endpoint
- OCR / form extraction service
- Field mapping logic
- Structured JSON response
- Validation + storage
Below is a practical setup that works for most stacks.
1) Choose a form recognition engine
Common options:
- Azure AI Document Intelligence (good for forms, receipts, invoices)
- Google Document AI
- Amazon Textract
- Open-source OCR like Tesseract + layout parsing
- Custom model if your forms are highly specific
If you want a managed API, Azure/AWS/Google are the easiest.
2) Create an API endpoint for uploads
Your backend should accept:
PDFJPGPNGTIFF
Example behavior:
- User uploads a file
- Backend stores it temporarily
- Backend sends it to the OCR/form recognition service
- Service returns extracted text/fields
- Backend normalizes output into JSON
Example endpoint design
POST /api/forms/extract- Request: multipart file upload
- Response: extracted fields in JSON
3) Process scanned PDFs and images
For scanned PDFs
- Send the PDF directly to the OCR/form service if supported
- If not, convert PDF pages to images first
- Run OCR page by page
For uploaded images
- Send image directly to OCR service
- Optionally preprocess:
- deskew
- denoise
- increase contrast
- rotate if needed
4) Map extracted data to fields
You usually want output like:
{
"full_name": "Jane Doe",
"date_of_birth": "1990-01-01",
"policy_number": "ABC12345",
"address": "123 Main St"
}
To do this, define field rules:
- exact keys from a known form template
- key-value matching
- regex for IDs, dates, phone numbers
- confidence thresholds
If the form is always the same, template-based extraction is best.
If forms vary, use a general document model plus custom post-processing.
5) Return a clean JSON response
Example response:
{
"success": true,
"document_type": "application_form",
"confidence": 0.94,
"fields": {
"first_name": "Jane",
"last_name": "Doe",
"email": "jane@example.com",
"phone": "+1-555-123-4567"
},
"warnings": [
"address field had low confidence"
]
}
6) Example using Azure Document Intelligence
Install SDK
pip install azure-ai-documentintelligence
Python example
from azure.ai.documentintelligence import DocumentIntelligenceClient
from azure.core.credentials import AzureKeyCredential
endpoint = "https://<your-resource>.cognitiveservices.azure.com/"
key = "<your-key>"
client = DocumentIntelligenceClient(endpoint=endpoint, credential=AzureKeyCredential(key))
with open("sample.pdf", "rb") as f:
poller = client.begin_analyze_document(
model_id="prebuilt-document",
analyze_request=f,
content_type="application/pdf"
)
result = poller.result()
for page in result.pages:
print("Page", page.page_number)
print(result.content)
If you have a custom form model, use your custom model_id instead of prebuilt-document.
7) Example API flow in FastAPI
from fastapi import FastAPI, UploadFile, File
import tempfile
app = FastAPI()
@app.post("/api/forms/extract")
async def extract_form(file: UploadFile = File(...)):
with tempfile.NamedTemporaryFile(delete=False) as tmp:
tmp.write(await file.read())
temp_path = tmp.name
# Send temp_path to OCR/form recognition service here
# Parse result and normalize to JSON
return {
"success": True,
"filename": file.filename,
"fields": {}
}
8) Important production considerations
Security
- Validate file type and size
- Scan uploads for malware
- Use authenticated access
- Store files in secure temporary storage
Reliability
- Use async jobs for large PDFs
- Add retries for OCR service failures
- Log extraction errors
Accuracy
- Use form templates when possible
- Add confidence scoring
- Allow manual review for low-confidence fields
Performance
- Cache repeated templates
- Process pages in parallel if supported
- Use queue workers for heavy processing
9) Recommended architecture
A solid production setup looks like this:
- Frontend: upload form
- API server: receives file
- Queue: Celery / RabbitMQ / SQS for async jobs
- OCR service: Azure / Textract / Document AI
- Database: store extracted fields
- Object storage: S3 / Blob Storage for original files
- Review UI: human correction for uncertain fields
10) Best practice for field extraction
If your forms are standardized:
- Train a custom model
- Use labeled samples
- Extract structured keys directly
If your documents vary:
- Use general OCR
- Use LLM post-processing to map text into a schema
- Add regex and heuristics
If you want, I can give you a complete working example in:
- Python + FastAPI
- Node.js + Express
- C# / .NET
- Azure Document Intelligence
- Amazon Textract