Skip to content

A production-ready Spring Boot REST API for personal finance management with JWT authentication, expense/income tracking, real-time analytics, and comprehensive CRUD operations. Built with Spring Security, MySQL, and modern best practices.

Notifications You must be signed in to change notification settings

seshathri044/expense-tracker-backend

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

6 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ’° ExpenseTracker Backend API

A production-ready Spring Boot REST API for personal finance management with JWT authentication, expense/income tracking, real-time analytics, and comprehensive CRUD operations. Built with Spring Security, MySQL, and modern best practices.

Spring Boot Java MySQL JWT

πŸ“‹ Table of Contents

✨ Features

Authentication & Authorization

  • πŸ” JWT-based authentication
  • πŸ”‘ Secure password encryption
  • πŸ‘€ User registration and login
  • πŸ”„ Token refresh mechanism
  • πŸ“§ Email notifications
  • πŸ”’ Role-based access control

Expense Management

  • βž• Create, read, update, and delete expenses
  • 🏷️ Categorize expenses
  • πŸ“Š Track spending patterns
  • πŸ” Filter and search expenses
  • πŸ“… Date-based expense tracking

Income Management

  • πŸ’΅ Record income transactions
  • πŸ“ˆ Track income sources
  • πŸ“Š Income analytics

Statistics & Analytics

  • πŸ“Š Financial statistics
  • πŸ“‰ Spending trends
  • πŸ’Ή Income vs Expense comparison
  • πŸ“… Monthly/Yearly reports

User Profile

  • πŸ‘€ User profile management
  • βš™οΈ Account settings
  • πŸ“§ Email preferences

πŸ› οΈ Tech Stack

Backend Framework

  • Spring Boot 3.x - Application framework
  • Spring Security - Authentication & Authorization
  • Spring Data JPA - Data persistence
  • Hibernate - ORM framework

Database

  • MySQL 8.0 - Primary database
  • HikariCP - Connection pooling

Security

  • JWT (JSON Web Tokens) - Stateless authentication
  • BCrypt - Password hashing

Build Tool

  • Maven - Dependency management

Additional Libraries

  • Lombok - Reduce boilerplate code
  • ModelMapper - Object mapping
  • Jakarta Validation - Input validation

πŸ“ Project Structure

ExpenseTracker/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ main/
β”‚   β”‚   β”œβ”€β”€ java/com/example/ExpenseTracker/
β”‚   β”‚   β”‚   β”œβ”€β”€ Controller/
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ AuthController.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ ExpenseController.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ IncomeController.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ ProfileController.java
β”‚   β”‚   β”‚   β”‚   └── StatsController.java
β”‚   β”‚   β”‚   β”‚
β”‚   β”‚   β”‚   β”œβ”€β”€ DTO/
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ ExpenseDTO.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ GraphDTO.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ IncomeDTO.java
β”‚   β”‚   β”‚   β”‚   └── StatsDTO.java
β”‚   β”‚   β”‚   β”‚
β”‚   β”‚   β”‚   β”œβ”€β”€ Entity/
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ Expense.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ Income.java
β”‚   β”‚   β”‚   β”‚   └── UserEntity.java
β”‚   β”‚   β”‚   β”‚
β”‚   β”‚   β”‚   β”œβ”€β”€ Filter/
β”‚   β”‚   β”‚   β”‚   └── JwtRequestFilter.java
β”‚   β”‚   β”‚   β”‚
β”‚   β”‚   β”‚   β”œβ”€β”€ IO/
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ AuthRequest.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ AuthResponse.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ ProfileRequest.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ ProfileResponse.java
β”‚   β”‚   β”‚   β”‚   └── ResetPasswordRequest.java
β”‚   β”‚   β”‚   β”‚
β”‚   β”‚   β”‚   β”œβ”€β”€ Repository/
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ ExpenseRepository.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ IncomeRepository.java
β”‚   β”‚   β”‚   β”‚   └── UserRepository.java
β”‚   β”‚   β”‚   β”‚
β”‚   β”‚   β”‚   β”œβ”€β”€ Service/
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ Stats/
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ StatsService.java
β”‚   β”‚   β”‚   β”‚   β”‚   └── StatsServiceImpl.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ AppUserDetailsService.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ EmailService.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ ExpenseService.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ ExpenseServiceImpl.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ IncomeService.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ IncomeServiceImpl.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ ProfileService.java
β”‚   β”‚   β”‚   β”‚   └── ProfileServiceImpl.java
β”‚   β”‚   β”‚   β”‚
β”‚   β”‚   β”‚   β”œβ”€β”€ SpringConfig/
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ CustomAuthenticationEntryPoint.java
β”‚   β”‚   β”‚   β”‚   └── SecurityConfig.java
β”‚   β”‚   β”‚   β”‚
β”‚   β”‚   β”‚   └── Util/
β”‚   β”‚   β”‚       └── JwtUtil.java
β”‚   β”‚   β”‚
β”‚   β”‚   └── resources/
β”‚   β”‚       β”œβ”€β”€ application.properties
β”‚   β”‚       β”œβ”€β”€ application-dev.properties
β”‚   β”‚       β”œβ”€β”€ application-prod.properties
β”‚   β”‚       β”œβ”€β”€ static/
β”‚   β”‚       └── templates/
β”‚   β”‚
β”‚   └── test/
β”‚       └── java/com/example/ExpenseTracker/
β”‚
β”œβ”€β”€ .gitignore
β”œβ”€β”€ pom.xml
└── README.md

πŸ“¦ Prerequisites

Before running this application, ensure you have the following installed:

πŸš€ Installation

1. Clone the Repository

git clone https://github.com/yourusername/expense-tracker-backend.git
cd expense-tracker-backend

2. Create MySQL Database

CREATE DATABASE expense_tracker;

3. Configure Application Properties

Update src/main/resources/application.properties:

# Application Name
spring.application.name=ExpenseTracker

# Database Configuration
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/expense_tracker?useSSL=false&serverTimezone=Asia/Kolkata&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=YOUR_PASSWORD

# JPA/Hibernate Configuration
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.properties.hibernate.format_sql=true

# JWT Configuration
jwt.secret.key=YOUR_SECRET_KEY_HERE

4. Build the Project

mvn clean install

5. Run the Application

mvn spring-boot:run

The application will start on http://localhost:8080

βš™οΈ Configuration

Environment-Specific Properties

Development (application-dev.properties)

spring.datasource.url=jdbc:mysql://localhost:3306/expense_tracker
spring.jpa.show-sql=true

Production (application-prod.properties)

spring.datasource.url=jdbc:mysql://your-production-db:3306/expense_tracker
spring.jpa.show-sql=false

JWT Configuration

Generate a secure secret key:

openssl rand -base64 64

Add to your properties file:

jwt.secret.key=<your-generated-key>

πŸ“š API Documentation

Base URL

http://localhost:8080

Authentication Endpoints

Register User

POST /api/auth/register
Content-Type: application/json

{
  "username": "john_doe",
  "email": "[email protected]",
  "password": "SecurePass123!"
}

Login

POST /api/auth/login
Content-Type: application/json

{
  "email": "[email protected]",
  "password": "SecurePass123!"
}

Response:

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "userId": 1,
  "email": "[email protected]",
  "username": "john_doe"
}

Expense Endpoints

All expense endpoints require JWT authentication:

Authorization: Bearer <your-jwt-token>

Create Expense

POST /api/expenses
Content-Type: application/json

{
  "title": "Grocery Shopping",
  "amount": 1500.00,
  "date": "2024-10-23",
  "category": "Food",
  "description": "Weekly groceries"
}

Get All Expenses

GET /api/expenses?page=0&size=10

Get Expense by ID

GET /api/expenses/{id}

Update Expense

PUT /api/expenses/{id}
Content-Type: application/json

{
  "title": "Updated Grocery Shopping",
  "amount": 1600.00,
  "date": "2024-10-23",
  "category": "Food",
  "description": "Weekly groceries - updated"
}

Delete Expense

DELETE /api/expenses/{id}

Income Endpoints

Create Income

POST /api/income
Content-Type: application/json

{
  "title": "Monthly Salary",
  "amount": 50000.00,
  "date": "2024-10-01",
  "category": "Salary",
  "description": "October salary"
}

Get All Income

GET /api/income?page=0&size=10

Update Income

PUT /api/income/{id}
Content-Type: application/json

Delete Income

DELETE /api/income/{id}

Statistics Endpoints

Get Dashboard Statistics

GET /api/stats/dashboard

Response:

{
  "totalIncome": 50000.00,
  "totalExpense": 25000.00,
  "balance": 25000.00,
  "latestIncomes": [...],
  "latestExpenses": [...],
  "minExpense": 100.00,
  "maxExpense": 5000.00
}

Get Chart Data

GET /api/stats/chart

Profile Endpoints

Get User Profile

GET /api/profile

Update Profile

PUT /api/profile
Content-Type: application/json

{
  "username": "john_doe_updated",
  "email": "[email protected]"
}

Reset Password

POST /api/profile/reset-password
Content-Type: application/json

{
  "oldPassword": "OldPass123!",
  "newPassword": "NewPass123!"
}

πŸ—„οΈ Database Schema

User Entity

CREATE TABLE user_entity (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(255) NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    password VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

Expense Entity

CREATE TABLE expense (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    title VARCHAR(255) NOT NULL,
    amount DECIMAL(19,2) NOT NULL,
    date DATE NOT NULL,
    category VARCHAR(100),
    description TEXT,
    user_id BIGINT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES user_entity(id)
);

Income Entity

CREATE TABLE income (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    title VARCHAR(255) NOT NULL,
    amount DECIMAL(19,2) NOT NULL,
    date DATE NOT NULL,
    category VARCHAR(100),
    description TEXT,
    user_id BIGINT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES user_entity(id)
);

πŸ”’ Security

Authentication Flow

  1. User registers/logs in with credentials
  2. Server validates credentials
  3. Server generates JWT token
  4. Client stores token (localStorage/sessionStorage)
  5. Client includes token in Authorization header for subsequent requests
  6. Server validates token and processes request

Password Security

  • Passwords are hashed using BCrypt algorithm
  • Minimum password requirements enforced
  • Secure password reset mechanism

CORS Configuration

Configure allowed origins in SecurityConfig.java:

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
    configuration.setAllowedHeaders(Arrays.asList("*"));
    configuration.setAllowCredentials(true);
    
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

πŸ§ͺ Testing

Run Tests

mvn test

Test Coverage

mvn clean test jacoco:report

πŸ› Error Handling

The API uses standard HTTP status codes:

Status Code Description
200 Success
201 Created
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
500 Internal Server Error

Error Response Format

{
  "timestamp": "2024-10-23T10:15:30",
  "status": 400,
  "error": "Bad Request",
  "message": "Invalid input data",
  "path": "/api/expenses"
}

πŸ“ˆ Performance Optimization

  • Connection Pooling: HikariCP for efficient database connections
  • Pagination: Implemented for large datasets
  • Caching: Strategic caching for frequently accessed data
  • Lazy Loading: Hibernate lazy loading for optimal performance

πŸš€ Deployment

Docker Deployment

Create a Dockerfile:

FROM openjdk:17-jdk-slim
WORKDIR /app
COPY target/expense-tracker-0.0.1-SNAPSHOT.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]

Build and run:

docker build -t expense-tracker-backend .
docker run -p 8080:8080 expense-tracker-backend

Cloud Deployment

The application is ready to deploy on:

  • AWS EC2
  • Heroku
  • Google Cloud Platform
  • Azure

🀝 Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Code Style

  • Follow Java naming conventions
  • Write meaningful commit messages
  • Add comments for complex logic
  • Write unit tests for new features

πŸ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ‘¨β€πŸ’» Author

Your Name

πŸ™ Acknowledgments

  • Spring Boot Community
  • JWT.io for authentication guidance
  • MySQL Documentation
  • Stack Overflow Community

πŸ“ž Support

For support, email [email protected] or open an issue in the repository.


⭐ Star this repository if you find it helpful!

Made with ❀️ and β˜•

About

A production-ready Spring Boot REST API for personal finance management with JWT authentication, expense/income tracking, real-time analytics, and comprehensive CRUD operations. Built with Spring Security, MySQL, and modern best practices.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages