Tutorial · Use Case

How to Build an Expense Tracking App with Receipt OCR

By Othmane M., founder of DocuParse API

2026-05-23 · 8 min readLast updated: 2026-10-27

The receipt upload feature is table stakes for any expense tracking app. Users photograph or upload a receipt; the app reads it and creates an expense entry automatically — no typing required. Here's how to build that feature from scratch using DocuParse API.

1
API endpoint
Auto
receipt parsing
React
+ any backend
Free
20 receipts/month
App architecture overview
📱
User uploads receipt
React/Next.js frontend
⚙️
Backend proxies request
Express / Next.js API route
🔗
DocuParse API extracts
Returns structured JSON
📊
Store + display
Database + expense dashboard
Architecture

What We're Building

A backend route that:

  1. Accepts a receipt file uploaded by a user
  2. Sends it to DocuParse API
  3. Creates an expense record from the extracted data
  4. Returns the expense to the client

The same pattern works whether you're building a mobile app backend, a web app, or an internal tool.

See what your app receives from the API
Upload a receipt. See the structured data your expense app would display.
Open Live Demo →
Free tier · 20 documents/month — free forever · No credit card · No account needed for the demo
Python · Node.js

Architecture Overview

text · 16 lines
[User's phone/browser]
       │ uploads receipt (PDF/JPG/PNG)
       ↓
[Your backend API]
       │ forwards file to DocuParse API
       ↓
[DocuParse API]
       │ returns structured JSON
       ↓
[Your backend API]
       │ creates expense record
       ↓
[Your database]
       │ saves expense
       ↓
[Returns expense to client]

The important thing: your API key never reaches the client. It stays on your server.


Node.js · Python
# main.py
import os
import json
import asyncio
from fastapi import FastAPI, UploadFile, Depends, HTTPException
from fastapi.responses import JSONResponse
import httpx
from pydantic import BaseModel
from typing import Optional, List

app = FastAPI()

class LineItem(BaseModel):
    description: Optional[str]
    quantity: Optional[float]
    price: Optional[str]
    line_total: Optional[str]
    vat_rate: Optional[str]

class Expense(BaseModel):
    merchant: Optional[str]
    amount: float
    tax: float
    currency: str
    date: Optional[str]
    receipt_id: Optional[str]
    payment_method: Optional[str]
    line_items: List[LineItem] = []


API = "https://docuparseapi.com/api/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['DOCUPARSE_API_KEY']}"}


async def call_docuparse(file_content: bytes, filename: str) -> dict:
    """Submit the file to DocuParse API, then fetch the result."""
    async with httpx.AsyncClient(timeout=30) as client:
        # 1. Submit
        submit = (await client.post(f"{API}/extract", headers=HEADERS,
                                    files={"file": (filename, file_content)})).json()
        if not submit.get("success"):
            code = submit.get("error", {}).get("code", "UNKNOWN")
            if code == "TOO_MANY_PAGES":
                raise HTTPException(status_code=422, detail="Split the PDF into parts of up to 20 pages")
            raise HTTPException(status_code=500, detail=f"Extraction failed: {code}")

        # 2. Fetch the result
        for _ in range(40):
            doc = (await client.get(f"{API}/documents/{submit['document_id']}",
                                    headers=HEADERS)).json()
            if doc["status"] == "completed":
                return doc["data"]
            if doc["status"] == "failed":
                raise HTTPException(status_code=422, detail="Extraction failed")
            await asyncio.sleep(1.5)
    raise HTTPException(status_code=504, detail="Extraction timed out")


@app.post("/api/expenses/upload", response_model=Expense)
async def upload_receipt(
    file: UploadFile,
    current_user = Depends(get_current_user)  # your auth dependency
):
    # Validate file type
    allowed_types = {"application/pdf", "image/jpeg", "image/png"}
    if file.content_type not in allowed_types:
        raise HTTPException(400, "Only PDF, JPG, and PNG files are supported")
    
    # Read file
    content = await file.read()
    
    # Extract data
    extracted = await call_docuparse(content, file.filename)
    
    # Map to expense model
    expense_data = Expense(
        merchant=extracted.get("merchant"),
        amount=float(extracted.get("total") or 0),
        tax=float(extracted.get("tax") or 0),
        currency=extracted.get("currency", "USD"),
        date=extracted.get("date"),
        receipt_id=extracted.get("receipt_id"),
        payment_method=extracted.get("payment_method"),
        line_items=[
            LineItem(**item) for item in extracted.get("line_items", [])
        ],
    )
    
    # Save to database (your ORM call here)
    saved = await db.expenses.create(
        user_id=current_user.id,
        **expense_data.dict()
    )
    
    return saved
Your expense app needs one endpoint.
20 documents/month — free forever. No credit card. Ships today.
Frontend

Frontend: Receipt Upload Component (React)

jsx · 89 lines
// components/ReceiptUpload.jsx
import { useState, useRef } from "react";

export function ReceiptUpload({ onExpenseCreated }) {
  const [status, setStatus] = useState("idle"); // idle | uploading | success | error
  const [expense, setExpense] = useState(null);
  const [errorMessage, setErrorMessage] = useState("");
  const fileInputRef = useRef(null);

  const handleFileChange = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    setStatus("uploading");
    setErrorMessage("");

    const formData = new FormData();
    formData.append("receipt", file);

    try {
      // Call YOUR backend — not DocuParse API directly
      const response = await fetch("/api/expenses/upload", {
        method: "POST",
        headers: {
          Authorization: `Bearer ${getAuthToken()}`,
        },
        body: formData,
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Upload failed");
      }

      setExpense(data.expense);
      setStatus("success");
      onExpenseCreated?.(data.expense);

    } catch (error) {
      setStatus("error");
      setErrorMessage(error.message);
    }
  };

  return (
    <div className="receipt-upload">
      <input
        ref={fileInputRef}
        type="file"
        accept=".pdf,.jpg,.jpeg,.png"
        onChange={handleFileChange}
        style={{ display: "none" }}
      />

      {status === "idle" && (
        <button onClick={() => fileInputRef.current?.click()}>
          Upload Receipt
        </button>
      )}

      {status === "uploading" && (
        <div>Reading your receipt...</div>
      )}

      {status === "success" && expense && (
        <div className="expense-preview">
          <p>✓ Expense created</p>
          <p>{expense.merchant} — {expense.currency} {expense.amount}</p>
          <p>{expense.date}</p>
          {expense.lineItems.length > 0 && (
            <ul>
              {expense.lineItems.map((item, i) => (
                <li key={i}>{item.description}: {item.line_total}</li>
              ))}
            </ul>
          )}
        </div>
      )}

      {status === "error" && (
        <div>
          <p>Error: {errorMessage}</p>
          <button onClick={() => setStatus("idle")}>Try again</button>
        </div>
      )}
    </div>
  );
}

Storage

Preventing Duplicate Expenses

A user might accidentally upload the same receipt twice. Each upload gets its own document_id, so compare the extracted fields — merchant, date, total and receipt ID — to catch likely duplicates:

javascript · 17 lines
// Before creating the expense record, check for duplicates
const existing = await db.expenses.findOne({
  where: {
    userId,
    merchant: extractedData.merchant,
    date: extractedData.date,
    amount: parseFloat(extractedData.total) || 0,
    receiptId: extractedData.receipt_id,
  }
});

if (existing) {
  return res.status(409).json({
    error: "This receipt has already been uploaded",
    expenseId: existing.id
  });
}

Dashboard

What to Show the User During Extraction

Extraction runs in the background. Use that time well:

  1. Immediately on upload: Show a progress indicator. "Reading your receipt..."
  2. On success: Pre-fill all form fields with extracted data. Let the user correct anything before saving.
  3. On failure: Give a specific, actionable error. "This image is too blurry — try taking the photo in better lighting, or upload a PDF." Not "something went wrong."

Pre-filling the form rather than silently saving is good UX — it builds trust by showing the user what was extracted and letting them verify it.


Pricing

Pricing

The receipt upload feature runs on the Starter plan (see current pricing), billed per document with up to 10 pages per document; 11–20 count as two. For most expense tracking apps, that's months of receipts covered at a price that rounds to noise.

Try it on your document — no sign-up

Ship

Next Steps

React · Express · Next.js · Any backend

Your expense tracker is a POST request away from working.

20 documents a month free, with full API access. No credit card. Webhooks on Starter and Pro.

More from the blog

All posts →