Skip to content

mantle-bearer/temp-fastapi

Repository files navigation

FastAPI Project Template

A production-ready FastAPI boilerplate with modern Python development practices, async SQLAlchemy 2.0, Alembic migrations, JWT authentication, and comprehensive tooling.

✨ Features

  • FastAPI: Modern, fast (high-performance) web framework
  • SQLAlchemy 2.0: Async/sync dual-engine database support
  • Alembic: Database migrations with auto-generation
  • JWT Authentication: Secure token-based auth with cookie support
  • UUID7: Modern UUID generation for database IDs
  • Pydantic: Data validation and settings management
  • Email System: FastAPI-Mail with Jinja2 templates
  • Development Tools: Black, isort, flake8, mypy, pytest
  • Docker Support: Multi-stage builds with development/production modes
  • UV Support: Modern Python package management
  • Comprehensive Logging: Structured logging setup

πŸ› οΈ Quick Start

Prerequisites

  • Python 3.11+
  • PostgreSQL (or SQLite for development)
  • Git

1. Clone and Setup

git clone <your-repo-url>
cd fastapi-template

2. Environment Configuration

Copy and configure your environment variables:

copy .env.sample .env

Edit .env with your actual configuration values.

3. Installation Methods

Option A: Using UV (Recommended)

# Install UV if you haven't
pip install uv

# Install dependencies
uv sync

# Run development server
uv run fastapi dev main.py

Option B: Using pip

# Create virtual environment
python -m venv venv
venv\Scripts\activate  # Windows
# source venv/bin/activate  # Linux/Mac

# Install dependencies
pip install -r requirements.txt

# Run development server
fastapi dev main.py

Option C: Using Docker

# Development with hot reload
docker-compose up

# Or build and run manually
docker build -t fastapi-template .
docker run -p 8000:8000 fastapi-template

4. Database Setup

# Run migrations
alembic upgrade head

# Create new migration (after model changes)
alembic revision --autogenerate -m "description"

πŸ“ Project Structure

fastapi-template/
β”œβ”€β”€ api/                          # Main API package
β”‚   β”œβ”€β”€ core/                     # Core functionality
β”‚   β”‚   β”œβ”€β”€ dependencies/         # Dependency injection
β”‚   β”‚   └── responses.py          # Response constants
β”‚   β”œβ”€β”€ db/                       # Database configuration
β”‚   β”‚   β”œβ”€β”€ database.py          # SQLAlchemy setup
β”‚   β”‚   └── enum.py              # Database enums
β”‚   β”œβ”€β”€ templates/               # Email templates
β”‚   β”œβ”€β”€ utils/                   # Utilities
β”‚   β”‚   β”œβ”€β”€ cookies.py          # OAuth2 with cookies
β”‚   β”‚   β”œβ”€β”€ response.py         # Response helpers
β”‚   β”‚   β”œβ”€β”€ security.py         # JWT utilities
β”‚   β”‚   └── settings.py         # Configuration
β”‚   └── v1/                     # API version 1
β”‚       β”œβ”€β”€ models/            # SQLAlchemy models
β”‚       β”œβ”€β”€ routes/            # API endpoints
β”‚       β”œβ”€β”€ schemas/           # Pydantic schemas
β”‚       └── services/          # Business logic
β”œβ”€β”€ alembic/                   # Database migrations
β”œβ”€β”€ tests/                     # Test suite
β”œβ”€β”€ main.py                    # FastAPI application
β”œβ”€β”€ requirements.txt           # Python dependencies
β”œβ”€β”€ pyproject.toml            # Project configuration
β”œβ”€β”€ docker-compose.yml        # Docker development setup
β”œβ”€β”€ Dockerfile               # Container configuration
└── .env.sample             # Environment template

πŸ”§ Development

Running the Application

# Development server with hot reload
fastapi dev main.py

# Production server
fastapi run main.py

# Custom host/port
fastapi dev main.py --host 0.0.0.0 --port 8080

Code Quality

# Format code
black .
isort .

# Lint code
flake8 .
mypy .

# Run tests
pytest
pytest -v --cov=api  # With coverage

Database Operations

# Create migration
alembic revision --autogenerate -m "add user table"

# Apply migrations
alembic upgrade head

# Rollback migration
alembic downgrade -1

# Check current version
alembic current

πŸ“š API Documentation

Once running, visit:

πŸ”‘ Authentication

The template includes JWT authentication with cookie support:

# Token in Authorization header
Authorization: Bearer <token>

# Or in cookie
Cookie: access_token=Bearer <token>

πŸ“§ Email System

Built-in email system with Jinja2 templates:

await send_mail(
    recipient="user@example.com",
    template_name="welcome.html",
    subject="Welcome!",
    context={"name": "John"}
)

🐳 Docker Deployment

Development

docker-compose up

Production

# Build production image
docker build --target production -t fastapi-template:prod .

# Run with environment variables
docker run -d \
  -p 8000:8000 \
  -e DB_HOST=your-db-host \
  -e JWT_SECRET_KEY=your-secret \
  fastapi-template:prod

βš™οΈ Configuration

Key environment variables:

Variable Description Default
APP_NAME Application name "FastAPI Template"
ENVIRONMENT Environment (development/production) "development"
DB_HOST Database host "localhost"
DB_TYPE Database type (postgresql/sqlite) "postgresql"
JWT_SECRET_KEY JWT secret key Required
FRONTEND_URL Frontend URL for CORS ""

See .env.sample for complete configuration options.

πŸ§ͺ Testing

# Run all tests
pytest

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

# Run specific test file
pytest tests/test_users.py

# Run with verbose output
pytest -v

πŸ“¦ Adding New Features

1. Add a New Model

# api/v1/models/your_model.py
from api.v1.models.base_mdel import BaseTableModel
from sqlalchemy import Column, String

class YourModel(BaseTableModel):
    __tablename__ = "your_table"
    
    name = Column(String, nullable=False)

2. Create Migration

# Import in api/v1/models/__init__.py
from .your_model import YourModel

# Generate migration
alembic revision --autogenerate -m "add your_model"
alembic upgrade head

3. Add API Routes

# api/v1/routes/your_routes.py
from fastapi import APIRouter
from api.utils.response import success_response

router = APIRouter()

@router.get("/")
async def list_items():
    return success_response(
        status_code=200,
        message="Items retrieved successfully",
        data={"items": []}
    )

4. Register Routes

# api/v1/routes/__init__.py
from .your_routes import router as your_router

api_router.include_router(your_router, prefix="/items", tags=["Items"])

🀝 Contributing

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

πŸ“„ License

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

πŸ†˜ Support


Happy coding! πŸŽ‰

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published