Skip to content

About

FastAPI CRUD BASE

Resources

Stars

3 stars

Watchers

1 watching

Forks

Repository files navigation

FastAPI Production-Ready Project

A production-ready FastAPI application with best practices, security, and scalability in mind.

Features

  • ✅ FastAPI - Modern, fast web framework
  • ✅ SQLAlchemy - ORM for database operations
  • ✅ Alembic - Database migrations
  • ✅ PostgreSQL - Production database
  • ✅ JWT Authentication - Secure token-based auth
  • ✅ Pydantic v2 - Data validation
  • ✅ Docker & Docker Compose - Containerization
  • ✅ Nginx - Reverse proxy
  • ✅ pytest - Testing framework
  • ✅ CORS Middleware - Cross-origin support
  • ✅ Logging - Structured logging
  • ✅ Environment Configuration - Secure config management

Project Structure

fastapi-project/
├── app/
│   ├── api/            # API endpoints
│   ├── core/           # Security, logging
│   ├── crud/           # Database operations
│   ├── db/             # Database config
│   ├── models/         # SQLAlchemy models
│   ├── schemas/        # Pydantic schemas
│   └── main.py         # Application entry point
├── tests/              # Test files
├── alembic/            # Database migrations
├── Dockerfile
├── docker-compose.yml
└── requirements.txt

Quick Start

1. Clone and Setup

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

# Copy environment file
cp .env.example .env

# Edit .env and update values (especially SECRET_KEY and passwords)
nano .env

2. Using Docker (Recommended)

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

# View logs
docker-compose logs -f

# Stop services
docker-compose down

The API will be available at:

3. Local Development (Without Docker)

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

# Start PostgreSQL (make sure it's running)

# Run migrations
alembic upgrade head

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

Database Migrations

# Create a new migration
alembic revision --autogenerate -m "Description of changes"

# Apply migrations
alembic upgrade head

# Rollback one migration
alembic downgrade -1

# View migration history
alembic history

Testing

# Run all tests
pytest

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

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

# Run with verbose output
pytest -v

API Endpoints

Authentication

  • POST /api/v1/auth/login - Login and get tokens

Users

  • POST /api/v1/users/ - Create new user
  • GET /api/v1/users/me - Get current user
  • PUT /api/v1/users/me - Update current user
  • GET /api/v1/users/ - Get all users (admin only)
  • GET /api/v1/users/{user_id} - Get user by ID (admin only)
  • PUT /api/v1/users/{user_id} - Update user (admin only)
  • DELETE /api/v1/users/{user_id} - Delete user (admin only)

Health

  • GET /health - Health check endpoint

Environment Variables

Key environment variables (see .env.example for all):

# Database
POSTGRES_SERVER=localhost
POSTGRES_USER=postgres
POSTGRES_PASSWORD=your_password
POSTGRES_DB=fastapi_db

# Security
SECRET_KEY=your-secret-key-min-32-characters
ACCESS_TOKEN_EXPIRE_MINUTES=30

# Environment
ENVIRONMENT=production
DEBUG=false

Production Deployment

Security Checklist

  • Change SECRET_KEY to a strong random value
  • Change all default passwords
  • Set DEBUG=false
  • Configure CORS origins properly
  • Set up SSL/TLS certificates
  • Enable Nginx rate limiting
  • Configure firewall rules
  • Set up monitoring and logging
  • Regular database backups
  • Update dependencies regularly

Generate Secret Key

python -c "import secrets; print(secrets.token_urlsafe(32))"

SSL/TLS Setup

For production, obtain SSL certificates (Let's Encrypt recommended):

# Install certbot
sudo apt-get install certbot

# Get certificate
sudo certbot certonly --standalone -d yourdomain.com

# Update nginx.conf with certificate paths
# Uncomment HTTPS server block in nginx.conf

Monitoring

Application Logs

# Docker logs
docker-compose logs -f api

# Local logs
tail -f logs/app.log

Database Monitoring

# Connect to database
docker-compose exec db psql -U postgres -d fastapi_db

# Check connections
SELECT * FROM pg_stat_activity;

Performance Optimization

  1. Database Indexing: Ensure proper indexes on frequently queried columns
  2. Connection Pooling: Configured in db/session.py
  3. Caching: Consider adding Redis for caching
  4. Rate Limiting: Configured in Nginx
  5. Workers: Adjust Uvicorn workers based on CPU cores

Contributing

  1. Fork the repository
  2. Create 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 Pull Request

License

This project is licensed under the MIT License.

Support

For issues and questions, please open an issue on GitHub.

About

FastAPI CRUD BASE

Resources

Stars

3 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages