Skip to content

Repository files navigation

FastAPI REST API Project

Python FastAPI MongoDB License Code Style

A modern, production-ready REST API built with FastAPI and MongoDB, following clean architecture principles, type safety, and industry best practices.


✨ Features

  • 🚀 High Performance: Async-first architecture with FastAPI and Motor (async MongoDB driver)
  • 🔐 Secure Authentication: JWT-based auth with bcrypt/passlib password hashing
  • 🧱 Clean Architecture: Clear separation between routes, services, repositories, and schemas
  • 🧪 Test-Ready: Comprehensive testing setup with pytest, pytest-asyncio, and factory-boy
  • 🐳 Docker Support: Production-ready containerization with docker-compose
  • 📦 Type Safety: Full type hints with Pydantic v2 validation
  • 🧹 Code Quality: Enforced linting and formatting with Ruff (Black-compatible)
  • 📚 Auto Documentation: Interactive Swagger UI and ReDoc out of the box

🛠️ Tech Stack

Category Technology
Framework FastAPI ≥0.135.1
Database MongoDB (PyMongo ≥4.16.0)
Authentication PyJWT ≥2.12.1, Passlib ≥1.7.4, bcrypt ≥5.0.0
Testing pytest ≥9.0.2, pytest-asyncio, pytest-cov, pytest-mock
Test Data factory-boy ≥3.3.3, Faker ≥40.8.0
Mocking mongomock ≥4.3.0
File Handling python-multipart ≥0.0.22
Code Quality Ruff ≥0.15.7 (linting + formatting)
Python ≥3.14

📁 Project Structure

├── app/
│   ├── core/                 # Config, settings, security and constants
│   ├── routes/               # API endpoint handlers (thin controllers)
│   ├── repositories/         # Data access layer (MongoDB operations)
│   ├── schemas/              # Pydantic models for validation & serialization
│   ├── services/             # Business logic & orchestration layer
│   ├── utils/                # Helpers, exceptions, logging
│   ├── dependencies/         # FastAPI DI: auth, DB sessions, permissions
│   └── main.py               # App factory, middleware, router registration
├── tests/
│   ├── unit/                 # Isolated unit tests
│   ├── integration/          # Service & repository integration tests
│   ├── api/                  # End-to-end API tests
│   ├── fixtures/             # Test data factories & mocks
│   └── conftest.py           # Pytest configuration & shared fixtures
├── Dockerfile                # Production container build
├── compose.yaml              # Multi-service orchestration (API + MongoDB)
├── .env.example              # Environment variable template
├── pyproject.toml            # Dependencies & tool configuration
└── README.md                 # This file

🚀 Getting Started

Prerequisites

  • Python ≥3.14
  • uv (recommended) or pip
  • Docker & Docker Compose (for containerized development)
  • MongoDB instance (local or remote)

1. Clone & Setup Environment

git clone <your-repo>
cd your-project

# Copy environment template
cp .env.example .env

# Edit .env with your configuration:
# - DATABASE_URL=mongodb://localhost:27017/your_db
# - SECRET_KEY=your-jwt-secret
# - ACCESS_TOKEN_EXPIRE_MINUTES=30

2. Install Dependencies

# Recommended: using uv (fast, modern Python package manager)
uv sync

# Alternative: using pip
pip install -e .

3. Run Locally

# Start development server with auto-reload
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

✅ Server running at: http://localhost:8000


🐳 Docker Development

# Build and start all services
docker compose up --build

# Run in detached mode
docker compose up -d

# View logs
docker compose logs -f

# Stop services
docker compose down

Access Points:

  • 🌐 API: http://localhost:8000
  • 📚 Swagger UI: http://localhost:8000/docs
  • 📖 ReDoc: http://localhost:8000/redoc
  • 🔍 Health Check: http://localhost:8000/health

📚 API Documentation

FastAPI automatically generates interactive API docs:

Interface URL Description
Swagger UI /docs Interactive testing with request/response examples
ReDoc /redoc Clean, readable API reference documentation
OpenAPI Schema /openapi.json Machine-readable API specification

🧪 Testing

Run the comprehensive test suite:

# Run all tests
pytest

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

# Run specific test file
pytest tests/api/test_users.py

# Run async tests with verbose output
pytest -v --asyncio-mode=auto

# Run tests inside Docker
docker compose run --rm api pytest

Test Structure:

  • tests/unit/ – Isolated logic tests (services, utils)
  • tests/integration/ – Repository & service layer tests
  • tests/api/ – End-to-end HTTP endpoint tests
  • tests/fixtures/ – Factory factories, mock data, and reusable test utilities

🧹 Code Quality & Linting

This project uses Ruff – a blazing-fast Python linter and formatter that replaces Flake8, isort, Black, pyupgrade, and more.

Quick Commands

# Check for issues (with auto-fix)
ruff check . --fix

# Format code (Black-compatible)
ruff format .

# Run full quality check (CI mode)
ruff check . && ruff format . --check

Enforced Rules

Category Rules Purpose
Code Quality E, W, F Catch bugs, undefined vars, syntax errors
Imports I Consistent, sorted imports (isort-compatible)
Best Practices B, C4, SIM, RET Prevent anti-patterns, simplify logic
Modern Python UP Encourage f-strings, pathlib, modern syntax
Naming N PEP 8 compliant naming conventions
Complexity mccabe ≤10 Maintain readable, testable functions
Ruff-Specific RUF Additional optimizations & improvements

See pyproject.toml for full configuration and per-file overrides.


🔐 Security Highlights

  • ✅ Passwords hashed with argon2
  • ✅ JWT tokens with configurable expiration & refresh logic
  • ✅ Environment-based secrets management (no hardcoded credentials)
  • ✅ CORS, rate limiting, and input validation ready for production
  • ✅ Dependency injection for secure, testable authentication flows

🏗️ Architecture Principles

  1. Separation of Concerns: Routes handle HTTP; services handle logic; repositories handle data.
  2. Dependency Injection: Leverage FastAPI's DI for clean, testable components.
  3. Type-First Development: Full type hints + Pydantic validation at boundaries.
  4. Testability: Each layer is independently testable with clear interfaces.
  5. Scalability: Modular, feature-based structure supports team growth and microservice evolution.

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feat/your-feature
  3. Commit changes: git commit -m 'feat: add your feature'
  4. Run checks: ruff check . && ruff format . --check && pytest
  5. Push and open a Pull Request

💡 Pro Tip: Use http://localhost:8000/docs during development to explore endpoints, test requests, and view response schemas in real-time.

Built with ❤️ using FastAPI and modern Python practices.

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages