A production-ready FastAPI template with best practices, proper structure, and essential tools for building scalable web APIs.
- FastAPI - Modern, fast web framework for building APIs
- SQLAlchemy 2.0 - Async ORM with type hints
- PostgreSQL - Production-ready database
- Alembic - Database migrations
- Pydantic Settings - Environment variable management
- JWT Authentication - Secure token-based auth
- Docker Compose - Easy development setup
- UV - Fast Python package manager
- Ruff - Lightning-fast linting and formatting
- Pre-commit - Code quality hooks
- Structured Logging - JSON and pretty console logging with
structlog
fastapi_project/
β
βββ app/
β βββ main.py # FastAPI application factory
β βββ api/
β β βββ v1/
β β βββ routes/
β β βββ users.py # User endpoints
β βββ models/ # Pydantic & SQLAlchemy models
β β βββ user.py
β βββ services/ # Business logic
β β βββ user_service.py
β βββ core/ # App settings, config
β β βββ config.py
β βββ db/ # Database setup
β β βββ database.py
β βββ utils/ # Helper functions
β βββ helpers.py
β
βββ alembic/ # Database migrations
βββ docker-compose.yml # PostgreSQL & Redis setup
βββ .env.example # Environment variables template
βββ pyproject.toml # Dependencies and tool config
βββ README.md # This file
# Clone the repository
git clone <your-repo-url>
cd py-backend
# Copy environment file
cp .env.example .env
# Edit .env with your settings (optional, defaults work for development)# Start PostgreSQL and Redis
docker-compose up -d
# Verify services are running
docker-compose ps# Install all dependencies
uv sync
# Or if you don't have uv installed:
pip install -r requirements.txt# Create your first migration
uv run alembic revision --autogenerate -m "Initial migration"
# Apply migrations
uv run alembic upgrade head# Development server
uv run fastapi dev app/main.py
# Or using uvicorn directly
uv run uvicorn app.main:app --reloadThe API will be available at:
- API: http://localhost:8000
- Interactive Docs: http://localhost:8000/api/v1/docs
- ReDoc: http://localhost:8000/api/v1/redoc
The application includes a comprehensive logging system with:
- Pretty Console Logging - Colored, readable logs for development
- Structured JSON Logging - Machine-readable logs for production
- File Rotation - Automatic log file management
- Performance Monitoring - Request timing and slow query detection
# View logs in real-time (pretty format)
tail -f logs/app.log
# For different log formats, set environment variables:
export CONSOLE_LOG_FORMAT=pretty # For colored console (default)
export LOG_FORMAT=json # For file logging formatSee LOGGING.md for detailed documentation.
# Format code
uv run ruff format
# Lint code
uv run ruff check
# Fix linting issues
uv run ruff check --fix# Install pre-commit hooks
uv run pre-commit install
# Run hooks manually
uv run pre-commit run --all-files# Create a new migration
uv run alembic revision --autogenerate -m "Add new table"
# Apply migrations
uv run alembic upgrade head
# Rollback migration
uv run alembic downgrade -1
# Migration history
uv run alembic history --verbose# Start all services
docker-compose up -d
# View logs
docker-compose logs -f
# Stop services
docker-compose down
# Clean up (removes volumes)
docker-compose down -v# Build production image
docker build -t fastapi-app .
# Run production container
docker run -p 8000:8000 fastapi-appGET /- Root endpointGET /health- Health checkGET /api/v1/docs- Interactive API documentationGET /api/v1/users- List all usersPOST /api/v1/users- Create new userGET /api/v1/users/{id}- Get user by IDPUT /api/v1/users/{id}- Update userDELETE /api/v1/users/{id}- Delete user
# Create a user
curl -X POST "http://localhost:8000/api/v1/users" \
-H "Content-Type: application/json" \
-d '{
"email": "[email protected]",
"first_name": "John",
"last_name": "Doe"
}'
# Get all users
curl "http://localhost:8000/api/v1/users"All configuration is managed through environment variables. See .env.example for all available options.
Key settings:
DEBUG- Enable debug modeSECRET_KEY- JWT secret key (change in production!)POSTGRES_*- Database connection settingsCORS_ORIGINS- Allowed CORS origins
The project uses PostgreSQL by default. Connection settings:
- Host:
localhost - Port:
5432 - Database:
fastapi_template - User:
postgres - Password:
password
-
Security:
- Change
SECRET_KEYto a secure random value - Set
DEBUG=False - Configure proper CORS origins
- Use environment variables for sensitive data
- Change
-
Database:
- Use a managed PostgreSQL service
- Run migrations:
alembic upgrade head - Set up database backups
-
Infrastructure:
- Use a proper WSGI server (Gunicorn + Uvicorn)
- Set up reverse proxy (Nginx)
- Configure logging
- Set up monitoring
# Install production dependencies
uv sync --no-dev
# Run with Gunicorn
gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorkerThe template is ready for testing. Add your tests in the tests/ directory.
# Install test dependencies
uv add --dev pytest pytest-asyncio httpx
# Run tests
uv run pytest- Create model in
app/models/ - Import in
app/models/__init__.py - Create migration:
alembic revision --autogenerate -m "Add new model" - Apply migration:
alembic upgrade head
- Create route file in
app/api/v1/routes/ - Create service in
app/services/ - Add router to
app/main.py
- Fork the repository
- Create a feature branch
- Make your changes
- Run tests and linting
- Submit a pull request
This project is licensed under the MIT License.
- FastAPI team for the amazing framework
- SQLAlchemy team for the excellent ORM
- All the open-source contributors who made this possible