Home Blog Reviews Best Picks Guides Tools Glossary Advertise Subscribe Free
Tech Frontline May 30, 2026 5 min read

How to Build an Automated Document Approval Workflow With AI: End-to-End Tutorial

A practical, step-by-step guide to automating document approvals with AI—from intake to final sign-off.

T
Tech Daily Shot Team
Published May 30, 2026
How to Build an Automated Document Approval Workflow With AI: End-to-End Tutorial

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


  1. Set Up Your Project Environment

    1. Clone the Starter Repository
      git clone https://github.com/your-org/ai-doc-approval-starter.git
      cd ai-doc-approval-starter
    2. Create a Python Virtual Environment
      python3 -m venv venv
      source venv/bin/activate
    3. Install Required Python Packages
      pip install fastapi uvicorn pymongo openai python-dotenv pydantic pdfplumber
    4. Set Up Environment Variables

      Copy .env.example to .env and 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.

  2. Ingest and Preprocess Documents

    1. Support PDF and DOCX Ingestion

      We'll use pdfplumber for PDFs and python-docx for DOCX files. Install the latter:

      pip install python-docx
    2. 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])
              
    3. 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.

  3. Integrate AI for Document Analysis & Approval Decision

    1. 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.

    2. 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()
              
    3. 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).

  4. Build the Approval Workflow API (FastAPI)

    1. 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}
              
    2. Run the API Locally
      uvicorn main:app --reload
    3. Test with curl or Postman
      curl -F "file=@sample.pdf" -F "criteria=Must be signed. Total under $10,000." http://localhost:8000/approve
              

      Should return {"decision": "APPROVED"} or {"decision": "REJECTED: ..."}.

  5. Store Approval Results in MongoDB

    1. 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"]
              
    2. 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()
      })
              
    3. Verify Data in MongoDB Atlas

      Login to Atlas dashboard > Collections > doc_approval.results to confirm inserts.

  6. Send Approval Notifications (Optional: Slack/MS Teams)

    1. 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)
              
    2. 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).

  7. Expose Your API for Webhooks with ngrok (for Testing)

    1. Start ngrok Tunnel
      ngrok http 8000

      Copy the public HTTPS URL and update WEBHOOK_URL in your .env.

    2. Test Webhook Integration

      Try submitting approval requests from external services using your ngrok URL.

  8. (Optional) Build a Simple Frontend Dashboard

    1. Initialize React App
      npx create-react-app doc-approval-ui
    2. Connect to FastAPI

      Use fetch or axios to POST files and criteria to your /approve endpoint. Display results and status.

    3. 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.


Common Issues & Troubleshooting


Next Steps

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.

workflow automation document approval AI tutorial step-by-step enterprise

Related Articles

Tech Frontline
Unlocking the Power of Custom AI Agents in Knowledge Workflow Automation
May 30, 2026
Tech Frontline
Rapid AI Workflow Prototyping: How to Build and Validate Automated Processes in 48 Hours
May 30, 2026
Tech Frontline
Blueprint: Automating Compliance Workflows in Healthcare with Minimal Code (2026)
May 29, 2026
Tech Frontline
Integrating AI Workflow Automation with Legacy ERP Systems: Pitfalls & Solutions
May 29, 2026
Free & Interactive

Tools & Software

100+ hand-picked tools personally tested by our team — for developers, designers, and power users.

🛠 Dev Tools 🎨 Design 🔒 Security ☁️ Cloud
Explore Tools →
Step by Step

Guides & Playbooks

Complete, actionable guides for every stage — from setup to mastery. No fluff, just results.

📚 Homelab 🔒 Privacy 🐧 Linux ⚙️ DevOps
Browse Guides →
Advertise with Us

Put your brand in front of 10,000+ tech professionals

Native placements that feel like recommendations. Newsletter, articles, banners, and directory features.

✉️
Newsletter
10K+ reach
📰
Articles
SEO evergreen
🖼️
Banners
Site-wide
🎯
Directory
Priority

Stay ahead of the tech curve

Join 10,000+ professionals who start their morning smarter. No spam, no fluff — just the most important tech developments, explained.