Category: Builder's Corner
Keyword: automated document approval workflow AI
Automated document approval is transforming business operations by reducing manual review, increasing throughput, and ensuring compliance. In this deep-dive tutorial, you'll learn how to build a robust, end-to-end automated document approval workflow using AI—complete with code examples, configuration, and practical troubleshooting.
If you're new to the topic or want a broader industry context, see our Pillar: The 2026 Guide to Automating AI-Driven Document Workflows Across Industries.
Prerequisites
- Technical Skills: Familiarity with Python, REST APIs, Docker, and basic webhooks.
- Tools & Versions:
- Python 3.10+
- Docker Desktop (latest)
- Node.js 18+ (for optional UI)
- ngrok (for webhook testing)
- OpenAI API key (or Azure OpenAI)
- MongoDB Atlas (free tier)
- Git
- Accounts: OpenAI, MongoDB Atlas, and (optionally) Slack or MS Teams for notifications.
- Sample Documents: PDFs or DOCXs for approval testing.
-
Set Up Your Project Environment
-
Clone the Starter Repository
git clone https://github.com/your-org/ai-doc-approval-starter.git
cd ai-doc-approval-starter
-
Create a Python Virtual Environment
python3 -m venv venv
source venv/bin/activate
-
Install Required Python Packages
pip install fastapi uvicorn pymongo openai python-dotenv pydantic pdfplumber
-
Set Up Environment Variables
Copy
.env.exampleto.envand fill in your API keys and MongoDB URI:cp .env.example .env
Edit
.env:OPENAI_API_KEY=sk-... MONGODB_URI=mongodb+srv://... WEBHOOK_URL=https://your-ngrok-url.io/webhook
Tip: For a more advanced, industry-specific workflow, see AI-Driven Document Workflow Automation in Finance: Key Use Cases, Pitfalls & ROI Metrics.
-
Clone the Starter Repository
-
Ingest and Preprocess Documents
-
Support PDF and DOCX Ingestion
We'll use
pdfplumberfor PDFs andpython-docxfor DOCX files. Install the latter:pip install python-docx
-
Create a Document Parsing Utility
In
utils/document_parser.py:import pdfplumber from docx import Document def extract_text_from_pdf(file_path): with pdfplumber.open(file_path) as pdf: return ' '.join(page.extract_text() for page in pdf.pages if page.extract_text()) def extract_text_from_docx(file_path): doc = Document(file_path) return ' '.join([para.text for para in doc.paragraphs if para.text]) -
Test Document Parsing
python utils/document_parser.py sample.pdf
Check output for expected text extraction.
For more on intelligent document processing, see Beyond OCR: Next-Gen IDP Solutions for AI Workflow Automation in 2026.
-
Support PDF and DOCX Ingestion
-
Integrate AI for Document Analysis & Approval Decision
-
Design Approval Criteria
Define your rules (e.g., "Must include signature", "Total amount < $10,000", etc.). We'll pass these as prompts to the AI.
-
Build the AI Approval Function
In
services/ai_approval.py:import openai def ai_approve_document(document_text, approval_criteria): prompt = f""" You are an expert compliance officer. Given the following approval criteria: {approval_criteria} And this document content: {document_text} Does this document meet all criteria? Reply with "APPROVED" or "REJECTED", and a brief reason. """ response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": prompt}], temperature=0.0, max_tokens=100, ) return response.choices[0].message.content.strip() -
Test the AI Approval Logic
python >>> from services.ai_approval import ai_approve_document >>> text = "This contract is signed by John Doe. Total: $9500." >>> criteria = "Must be signed. Total amount under $10,000." >>> print(ai_approve_document(text, criteria)) APPROVED
For advanced review logic (e.g., contract-specific), see Automating Contract Review with AI: Tools, Best Practices, and Workflow Templates (2026).
-
Design Approval Criteria
-
Build the Approval Workflow API (FastAPI)
-
Create the FastAPI App
In
main.py:from fastapi import FastAPI, UploadFile, File, Form from utils.document_parser import extract_text_from_pdf, extract_text_from_docx from services.ai_approval import ai_approve_document app = FastAPI() @app.post("/approve") async def approve_document(file: UploadFile = File(...), criteria: str = Form(...)): filename = file.filename contents = await file.read() with open(f"temp/{filename}", "wb") as f: f.write(contents) if filename.endswith(".pdf"): text = extract_text_from_pdf(f"temp/{filename}") elif filename.endswith(".docx"): text = extract_text_from_docx(f"temp/{filename}") else: return {"error": "Unsupported file type"} result = ai_approve_document(text, criteria) return {"decision": result} -
Run the API Locally
uvicorn main:app --reload
-
Test with curl or Postman
curl -F "file=@sample.pdf" -F "criteria=Must be signed. Total under $10,000." http://localhost:8000/approveShould return
{"decision": "APPROVED"}or{"decision": "REJECTED: ..."}.
-
Create the FastAPI App
-
Store Approval Results in MongoDB
-
Connect to MongoDB Atlas
In
services/db.py:from pymongo import MongoClient import os client = MongoClient(os.getenv("MONGODB_URI")) db = client["doc_approval"] results = db["results"] -
Save Results After Approval
Update your FastAPI route in
main.py:from services.db import results results.insert_one({ "filename": filename, "criteria": criteria, "decision": result, "timestamp": datetime.utcnow() }) -
Verify Data in MongoDB Atlas
Login to Atlas dashboard > Collections >
doc_approval.resultsto confirm inserts.
-
Connect to MongoDB Atlas
-
Send Approval Notifications (Optional: Slack/MS Teams)
-
Integrate with Slack Incoming Webhooks
pip install requests
In
services/notify.py:import requests import os def send_slack_notification(message): webhook_url = os.getenv("SLACK_WEBHOOK_URL") if webhook_url: payload = {"text": message} requests.post(webhook_url, json=payload) -
Trigger Notification on Decision
In
main.py:from services.notify import send_slack_notification send_slack_notification(f"Document '{filename}' was {result}")
For real-time escalation logic, see How to Build a Proactive AI Customer Service Workflow (With Real-Time Escalation Logic).
-
Integrate with Slack Incoming Webhooks
-
Expose Your API for Webhooks with ngrok (for Testing)
-
Start ngrok Tunnel
ngrok http 8000
Copy the public HTTPS URL and update
WEBHOOK_URLin your.env. -
Test Webhook Integration
Try submitting approval requests from external services using your ngrok URL.
-
Start ngrok Tunnel
-
(Optional) Build a Simple Frontend Dashboard
-
Initialize React App
npx create-react-app doc-approval-ui
-
Connect to FastAPI
Use
fetchoraxiosto POST files and criteria to your/approveendpoint. Display results and status. -
Sample File Upload Component
import React, { useState } from 'react'; function ApprovalForm() { const [file, setFile] = useState(null); const [criteria, setCriteria] = useState(''); const [result, setResult] = useState(''); const handleSubmit = async (e) => { e.preventDefault(); const formData = new FormData(); formData.append('file', file); formData.append('criteria', criteria); const res = await fetch('http://localhost:8000/approve', { method: 'POST', body: formData, }); const data = await res.json(); setResult(data.decision); }; return ( <form onSubmit={handleSubmit}> <input type="file" onChange={e => setFile(e.target.files[0])} /> <input type="text" value={criteria} onChange={e => setCriteria(e.target.value)} placeholder="Approval criteria" /> <button type="submit">Submit</button> {result && <div>Result: {result}</div>} </form> ); } export default ApprovalForm;
Screenshot: Approval form UI with file upload, criteria input, and "APPROVED/REJECTED" result display.
-
Initialize React App
Common Issues & Troubleshooting
-
AI Returns Inconsistent Decisions
Ensure your approval criteria are explicit and concise. Use temperature=0 for deterministic output. -
PDF/DOCX Text Extraction Fails
Some PDFs are image-based. For these, integrate OCR tools likepytesseract. See Beyond OCR: Next-Gen IDP Solutions for AI Workflow Automation in 2026. -
API Key or DB Connection Errors
Double-check your.envvariables and network/firewall settings. -
ngrok Tunnel Not Accessible
Ensure ngrok is running and your FastAPI server is accessible on localhost:8000. -
Slack Notifications Not Sent
Confirm your Slack webhook URL and check for errors in the logs.
Next Steps
- Expand Workflow Complexity: Add multi-stage approvals, escalation logic, or integrate with e-signature platforms.
- Enhance Security: Implement authentication (OAuth2/JWT), audit logging, and document redaction as needed.
- Scale for Production: Containerize with Docker Compose, deploy to cloud (AWS/GCP/Azure), and set up CI/CD pipelines.
- Explore Industry-Specific Templates: See our guide to optimizing AI document workflows for healthcare for compliance and clinical best practices.
- Stay Updated: For the latest trends, check Microsoft’s SynapseGPT API: What Its Launch Means for Automated Enterprise Workflows.
Ready to take your document automation further? Dive deeper with our ultimate 2026 guide to AI-driven document workflows—covering industry trends, ROI, and future-proofing your stack.