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.
- π JWT-Based Stateless Authentication: Secure token verification (
Authorization: Bearer <token>) usingPyJWTwith 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.
- CORS Protection: Fine-grained Cross-Origin Resource Sharing controls (
- π 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.
- Complete JSON RESTful API (
- π Interactive REST API Documentation: Built-in visual API docs viewer at
/api/docs.
+-------------------------------------------------------------+
| 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 |
+-------------------------------------------------------------+
| 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 |
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
All protected endpoints require the following header:
Authorization: Bearer <your_jwt_token>
Content-Type: application/json| 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 |
curl -X POST http://127.0.0.1:5000/api/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"johndoe", "password":"securepassword123"}'{
"status": "success",
"message": "Authentication successful.",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "Bearer",
"expires_in_hours": 24,
"user": {
"id": "6732f9104b2b1a8d01a4e101",
"username": "johndoe"
}
}| 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) |
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"
}'| 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) |
| 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) |
- Python 3.10+
- MongoDB running locally on default port
27017or a MongoDB Atlas connection URI
# 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.txtCreate a .env file from the provided .env.example:
cp .env.example .envEnsure 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_keypython app.py- Web Dashboard: http://127.0.0.1:5000/
- Interactive REST API Docs: http://127.0.0.1:5000/api/docs
- API Root / Health Check: http://127.0.0.1:5000/api
- Import the endpoints into Postman or use cURL.
- Call
POST /api/auth/registerto create a test user. - Call
POST /api/auth/loginand copy the returnedtoken. - In Postman, go to Authorization tab -> Type: Bearer Token -> paste the token.
- Execute requests against
/api/transactions,/api/budgets, and/api/analytics/summary.
Distributed under the MIT License. See LICENSE for more information.
Crafted by Utsho Roy β’ Backend & Software Engineer