Skip to content

mrroot5/fastapi-wallet

Repository files navigation

FastAPI Wallet

A virtual wallet simulation API built with FastAPI, featuring role-based access control, scheduled transactions, and comprehensive transaction management.

Features

Core Functionality

  • User Management: Registration, authentication (JWT), and profile management
  • Multi-Wallet Support: Users can have multiple wallets with different currencies
  • Transaction Types: Deposits, withdrawals, and transfers (in/out)
  • Scheduled Transactions: One-time scheduled or recurring transactions (daily, weekly, monthly)
  • Transaction Management: Create, view, and cancel transactions with cursor-based pagination
  • Role-Based Access Control (RBAC):
    • Regular users: Manage their own wallets and transactions
    • Staff users: Access and manage all wallets and transactions
    • Superusers: All staff permissions plus ability to modify wallet balances directly

Technical Features

  • Monetary Precision: Uses Decimal type with 6 decimal places to prevent floating-point errors
  • Async/Await: Fully asynchronous for high performance
  • Database: PostgreSQL with async SQLAlchemy 2.0
  • Background Tasks: Celery + Redis for processing scheduled/recurring transactions
  • Database Migrations: Alembic for schema management
  • Comprehensive Testing: Integration and unit tests with pytest
  • Type Safety: Full type hints with strict MyPy checking
  • Code Quality: Ruff linting with strict rules
  • Docker Support: Multi-container setup with Docker Compose

Project Structure

fastapi-wallet/
├── app/
│   ├── core/
│   │   ├── config.py           # Settings and configuration
│   │   ├── database.py         # Database session management
│   │   └── security.py         # Password hashing and JWT
│   ├── models/
│   │   ├── base.py             # Base model with UUID and timestamps
│   │   ├── user.py             # User model with roles
│   │   ├── wallet.py           # Wallet model with balance
│   │   └── transaction.py      # Transaction model with scheduling
│   ├── schemas/
│   │   ├── user.py             # Pydantic schemas for users
│   │   ├── wallet.py           # Pydantic schemas for wallets
│   │   ├── transaction.py      # Pydantic schemas for transactions
│   │   └── pagination.py       # Cursor-based pagination schemas
│   ├── services/
│   │   ├── user_service.py     # User business logic
│   │   ├── wallet_service.py   # Wallet business logic
│   │   └── transaction_service.py  # Transaction business logic
│   ├── routers/
│   │   ├── auth.py             # Registration and login endpoints
│   │   ├── users.py            # User management endpoints
│   │   ├── wallets.py          # Wallet CRUD endpoints
│   │   └── transactions.py     # Transaction endpoints
│   ├── tasks/
│   │   ├── celery_app.py       # Celery configuration
│   │   └── transaction_tasks.py  # Scheduled transaction processor
│   ├── dependencies.py         # FastAPI dependencies (auth, RBAC)
│   └── main.py                 # FastAPI application entry point
├── alembic/
│   ├── versions/               # Database migration files
│   ├── env.py                  # Alembic environment config
│   └── script.py.mako          # Migration template
├── tests/
│   ├── conftest.py             # Pytest fixtures
│   ├── test_auth_integration.py
│   ├── test_users_integration.py
│   ├── test_wallets_integration.py
│   ├── test_transactions_integration.py
│   └── test_role_permissions.py  # Unit tests for RBAC
├── docker-compose.yml          # Multi-container Docker setup
├── Dockerfile                  # Application container
├── .env.example                # Environment variables template
├── pyproject.toml              # Poetry dependencies and config
├── CLAUDE.md                   # Claude Code guidelines
├── FUTURE.md                   # Future feature ideas
└── README.md                   # This file

Prerequisites

  • Python 3.12.3+
  • Poetry 1.8+
  • Docker & Docker Compose (optional, recommended)

Installation & Setup

Option 1: Docker Compose (Recommended)

# Clone repository
git clone <your-repo-url>
cd fastapi-wallet

# Copy environment variables
cp .env.example .env

# Start all services (PostgreSQL, Redis, FastAPI, Celery)
docker-compose up --build

# Run database migrations (in another terminal)
docker-compose exec app alembic upgrade head

# Create a superuser (optional)
docker-compose exec app python -m app.scripts.create_superuser

The API will be available at http://localhost:8000

Option 2: Local Development

# Install Poetry (if not installed)
curl -sSL https://install.python-poetry.org | python3 -

# Clone repository
git clone <your-repo-url>
cd fastapi-wallet

# Install dependencies
poetry install

# Copy environment variables and configure
cp .env.example .env
# Edit .env with your database credentials

# Start PostgreSQL and Redis (via Docker)
docker-compose up -d db redis

# Run database migrations
poetry run alembic upgrade head

# Start the FastAPI server
poetry run uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

# In separate terminals, start Celery worker and beat
poetry run celery -A app.tasks.celery_app worker --loglevel=info
poetry run celery -A app.tasks.celery_app beat --loglevel=info

API Endpoints

Authentication

  • POST /api/auth/register - Register new user (auto-creates default wallet)
  • POST /api/auth/login - Login and get JWT token

Users

  • GET /api/users/me - Get current user profile
  • PATCH /api/users/me - Update current user
  • DELETE /api/users/me - Soft delete current user

Wallets

  • GET /api/wallets - List user's wallets
  • POST /api/wallets - Create new wallet
  • GET /api/wallets/{id} - Get wallet by ID
  • PATCH /api/wallets/{id} - Update wallet

Transactions

  • POST /api/transactions - Create transaction (immediate/scheduled/recurring)
  • GET /api/transactions?wallet_id={id} - List transactions (cursor-paginated)
  • GET /api/transactions/{id} - Get transaction by ID
  • PATCH /api/transactions/{id}/cancel - Cancel pending transaction

Documentation

  • GET /api/docs - Swagger UI
  • GET /api/redoc - ReDoc
  • GET /health - Health check

Validation Rules

Passwords

  • Minimum 8 characters
  • At least 1 number
  • At least 1 uppercase letter

Transactions

  • Minimum amount: €1.00
  • Amount must be positive
  • Wallet balance must remain >= 0

Wallets

  • Currency: 3-letter code (e.g., EUR, USD)
  • Balance uses Decimal with 6 decimal places
  • Balance cannot be negative

Testing

# Run all tests
poetry run pytest

# Run with coverage
poetry run pytest --cov=app --cov-report=html

# Run specific test file
poetry run pytest tests/test_auth_integration.py

# Run tests with output
poetry run pytest -v -s

Code Quality

# Lint code
poetry run ruff check .

# Auto-fix linting issues
poetry run ruff check --fix .

# Type checking
poetry run mypy .

Database Migrations

# Create a new migration
poetry run alembic revision --autogenerate -m "description"

# Apply migrations
poetry run alembic upgrade head

# Rollback migration
poetry run alembic downgrade -1

# View migration history
poetry run alembic history

Production Deployment

# Build and run with Docker Compose
docker-compose -f docker-compose.prod.yml up --build -d

# Or run directly with Uvicorn
poetry run uvicorn app.main:app --host 0.0.0.0 --port 8000 --workers 4

Production Checklist

  • Change SECRET_KEY in .env
  • Set DEBUG=False
  • Use strong database credentials
  • Enable HTTPS
  • Set up monitoring and logging
  • Configure backup strategy
  • Set up rate limiting
  • Review CORS settings

Architecture Decisions

Why Decimal Instead of Float?

Monetary values use Decimal to prevent floating-point precision errors:

# Bad (float precision issues)
0.1 + 0.2 = 0.30000000000000004

# Good (exact decimal precision)
Decimal("0.1") + Decimal("0.2") = Decimal("0.3")

Why UUID Instead of Integer IDs?

  • Security: Prevents ID enumeration attacks
  • Distributed Systems: No collision in distributed databases
  • Privacy: Harder to guess or predict IDs

Why Cursor-Based Pagination?

  • Consistency: No missing items when data changes
  • Performance: More efficient for large datasets
  • Ordering: Based on updated_at for most recent items first

Why Soft Deletes?

  • Audit Trail: Maintain history for compliance
  • Data Integrity: Preserve relationships (user → wallet → transactions)
  • Recovery: Ability to restore deleted accounts

Future Enhancements

See FUTURE.md for planned features including:

  • Currency conversion with live exchange rates
  • Transaction fees
  • Multi-factor authentication (MFA)
  • Advanced analytics and reporting
  • Webhook notifications
  • And more...

Contributing

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

License

MIT

About

A simple FastAPI wallet example

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages