Skip to content

mrroot5/fastapi-wallet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

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

 
 
 

Languages