Skip to content

About

Personal Finance & Expense Analytics Web Application and RESTful API built with Flask, PyMongo (MongoDB), PyJWT, and Chart.js.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

5 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ’° Smart Expense Tracker & Financial Analytics API

Python Flask MongoDB JWT Auth Chart.js License: MIT

A robust, full-featured Personal Finance Tracking & Analytics Web Application and RESTful API engineered with Python, Flask, MongoDB (PyMongo), and Chart.js.

The system features stateless JWT (JSON Web Token) authentication, automated CORS controls, strict input sanitization & parameter validation, real-time category-wise budget warnings, and dynamic financial analytics pipelines.


🌟 Key Highlights & Features

  • πŸ” JWT-Based Stateless Authentication: Secure token verification (Authorization: Bearer <token>) using PyJWT with configurable expiration, alongside salted password hashing (werkzeug.security).
  • πŸ›‘οΈ API Security Best Practices:
    • CORS Protection: Fine-grained Cross-Origin Resource Sharing controls (flask-cors) for decoupled frontend or mobile clients.
    • Input Sanitization & Validation: Custom validation layer (validators.py) enforcing alphanumeric constraints, numeric boundary checks, date format verification, and XSS sanitization.
  • πŸ“Š Interactive Financial Analytics:
    • Category-wise expense distribution powered by Chart.js (Pie & Doughnut charts).
    • 12-Month income vs. expense trends (Bar & Line charts).
    • Net savings and savings-rate percentage calculations.
  • 🎯 Category Budget Limits & Alerts: Set monthly budget thresholds per expense category; automatically flags over-budget spending and calculates remaining balance in real time.
  • πŸ—„οΈ MongoDB Aggregation Pipelines: High-performance NoSQL multi-stage aggregation queries for instant monthly summaries, category totals, and yearly comparisons.
  • 🌐 Dual Interface Support:
    • Complete JSON RESTful API (/api/...) for programmatic consumption, mobile apps, or headless frontends.
    • Responsive Web Dashboard (/) built with Bootstrap 5 and FontAwesome.
  • πŸ“„ Interactive REST API Documentation: Built-in visual API docs viewer at /api/docs.

πŸ—οΈ System Architecture

+-------------------------------------------------------------+
|                Clients (Web Browser / Postman / cURL)       |
+------------------------------+------------------------------+
                               |
               HTTP Requests (JSON / Web Forms)
               Authorization: Bearer <JWT Token>
                               |
                               v
+-------------------------------------------------------------+
|                     Flask Application Layer                 |
|  - CORS Handler (flask-cors)                                |
|  - JWT Authentication Middleware (@jwt_required via PyJWT)  |
|  - Input Validation & Sanitization Engine (validators.py)   |
+---------------+------------------------------+--------------+
                |                              |
      Web Controller (/...)          REST Controller (/api/...)
                |                              |
                v                              v
        Jinja2 Templates               JSON Responses
        (Dashboard, Charts)            (Status, Data, Errors)
                \                              /
                 v                            v
+-------------------------------------------------------------+
|                     MongoDB Database (PyMongo)               |
|  - users        : Credentials (hashed) & profile info       |
|  - transactions : Incomes & Expenses with category & date   |
|  - budgets      : Monthly category thresholds & limits      |
+-------------------------------------------------------------+

πŸ› οΈ Tech Stack

Layer Technologies
Backend Framework Python 3.10+, Flask, Werkzeug
Authentication & Tokens PyJWT (HS256 Bearer Token Verification)
Database MongoDB (NoSQL) via PyMongo driver
Security & Middleware Flask-CORS, Input Sanitization, HTML entity escaping
Visualization & UI Chart.js, HTML5, CSS3, Bootstrap 5, FontAwesome
Data Export JSON Data Serializer

πŸ“‚ Project Structure

smart-expense-tracker/
β”œβ”€β”€ app.py              # Main Flask application (REST API & Web UI routes)
β”œβ”€β”€ auth_jwt.py         # JWT token generator, decoder, and @jwt_required decorator
β”œβ”€β”€ config.py           # Configuration loader (env vars & database settings)
β”œβ”€β”€ validators.py       # Input sanitization and parameter validation routines
β”œβ”€β”€ requirements.txt    # Project dependencies
β”œβ”€β”€ .env.example        # Environment variable template
β”œβ”€β”€ .gitignore          # Git exclusion rules
β”œβ”€β”€ static/
β”‚   └── style.css       # Custom stylesheet & theme styling
└── templates/
    β”œβ”€β”€ api_docs.html   # Interactive REST API documentation view
    β”œβ”€β”€ base.html       # Base layout with sidebar navigation
    β”œβ”€β”€ dashboard.html  # Main metrics dashboard
    β”œβ”€β”€ analytics.html  # Chart.js visualization graphs
    β”œβ”€β”€ transactions.html # Transaction history table
    β”œβ”€β”€ add_transaction.html # Add transaction form
    β”œβ”€β”€ budgets.html    # Budget thresholds and limits
    β”œβ”€β”€ login.html      # Login page
    └── signup.html     # Registration page

πŸ“‘ REST API Reference

All protected endpoints require the following header:

Authorization: Bearer <your_jwt_token>
Content-Type: application/json

1. Authentication Endpoints

Method Endpoint Description Auth Required
POST /api/auth/register Register a new user No
POST /api/auth/login Login and receive signed JWT token No
GET /api/auth/profile Get current user's profile and stats Yes (Bearer)
POST /api/auth/verify Verify token validity No

Example Login Request:

curl -X POST http://127.0.0.1:5000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username":"johndoe", "password":"securepassword123"}'

Example Login Response (200 OK):

{
  "status": "success",
  "message": "Authentication successful.",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in_hours": 24,
  "user": {
    "id": "6732f9104b2b1a8d01a4e101",
    "username": "johndoe"
  }
}

2. Transactions Endpoints

Method Endpoint Description Auth Required
GET /api/transactions List transactions with filters (?type=, ?category=, ?month=) Yes (Bearer)
POST /api/transactions Create a new transaction with validation Yes (Bearer)
GET /api/transactions/<id> Retrieve a single transaction Yes (Bearer)
PUT / PATCH /api/transactions/<id> Update an existing transaction Yes (Bearer)
DELETE /api/transactions/<id> Delete a transaction Yes (Bearer)

Example Create Transaction Request:

curl -X POST http://127.0.0.1:5000/api/transactions \
  -H "Authorization: Bearer <your_jwt_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "expense",
    "category": "Groceries",
    "amount": 54.20,
    "date": "2026-10-01",
    "notes": "Weekly household essentials"
  }'

3. Budgets Endpoints

Method Endpoint Description Auth Required
GET /api/budgets?month=YYYY-MM List budgets with calculated spending & over-budget flag Yes (Bearer)
POST /api/budgets Set or update a monthly category budget limit Yes (Bearer)
DELETE /api/budgets/<id> Delete a category budget limit Yes (Bearer)

4. Financial Analytics Endpoints (Chart.js Data Feeds)

Method Endpoint Description Auth Required
GET /api/analytics/summary?month=YYYY-MM Total income, expense, net balance & savings rate Yes (Bearer)
GET /api/analytics/category-breakdown?month=YYYY-MM Category distribution array for Pie / Doughnut charts Yes (Bearer)
GET /api/analytics/monthly-trend Multi-month historical data for Bar / Line charts Yes (Bearer)
GET /api/analytics/yearly-trend Yearly financial totals Yes (Bearer)
GET /api/export Export user transactions in JSON format Yes (Bearer)

πŸš€ Getting Started

1. Prerequisites

  • Python 3.10+
  • MongoDB running locally on default port 27017 or a MongoDB Atlas connection URI

2. Installation & Setup

# 1. Clone the repository
git clone https://github.com/utsho261/smart-expense-tracker.git
cd smart-expense-tracker

# 2. Create a virtual environment
python -m venv venv

# Windows (PowerShell):
venv\Scripts\Activate.ps1
# macOS / Linux:
source venv/bin/activate

# 3. Install dependencies
pip install -r requirements.txt

3. Environment Configuration

Create a .env file from the provided .env.example:

cp .env.example .env

Ensure your configuration points to your MongoDB instance:

MONGO_URI=mongodb://localhost:27017/
DATABASE_NAME=smart_expense
SECRET_KEY=your_secure_random_session_secret
JWT_SECRET_KEY=your_jwt_secret_signing_key

4. Running the Application

python app.py

πŸ§ͺ Testing the API with Postman

  1. Import the endpoints into Postman or use cURL.
  2. Call POST /api/auth/register to create a test user.
  3. Call POST /api/auth/login and copy the returned token.
  4. In Postman, go to Authorization tab -> Type: Bearer Token -> paste the token.
  5. Execute requests against /api/transactions, /api/budgets, and /api/analytics/summary.

πŸ“„ License

Distributed under the MIT License. See LICENSE for more information.


Crafted by Utsho Roy β€’ Backend & Software Engineer

About

Personal Finance & Expense Analytics Web Application and RESTful API built with Flask, PyMongo (MongoDB), PyJWT, and Chart.js.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages