A comprehensive FastAPI backend scaffold with SQLAlchemy, Alembic, Pydantic, authentication, and email capabilities.
- FastAPI: Modern, fast web framework for building APIs
- SQLAlchemy: Powerful ORM for database operations
- Alembic: Database migration tool
- Pydantic: Data validation using Python type annotations
- Authentication: JWT-based authentication with password hashing
- Email Support: SMTP email configuration
- Structured Logging: Centralized logging setup
- Error Handling: Custom exception classes
- Repository Pattern: Clean architecture with separation of concerns
- Service Layer: Business logic abstraction
- Environment Management: Pydantic settings with
.envsupport
.
├── app/
│ ├── __init__.py
│ ├── api/
│ │ ├── __init__.py
│ │ ├── deps.py # Dependencies (authentication, etc.)
│ │ └── v1/
│ │ ├── __init__.py
│ │ ├── api.py # API router aggregation
│ │ ├── auth.py # Authentication endpoints
│ │ └── health.py # Health check endpoint
│ ├── core/
│ │ ├── __init__.py
│ │ ├── config.py # Pydantic settings
│ │ ├── database.py # Database configuration
│ │ ├── security.py # Security utilities
│ │ ├── logging.py # Logging configuration
│ │ └── exceptions.py # Custom exceptions
│ ├── models/
│ │ ├── __init__.py
│ │ └── user.py # SQLAlchemy models
│ ├── repositories/
│ │ ├── __init__.py
│ │ ├── base.py # Base CRUD operations
│ │ └── user.py # User repository
│ ├── services/
│ │ ├── __init__.py
│ │ └── user.py # User business logic
│ └── main.py # FastAPI application entry point
├── alembic/
│ ├── versions/ # Migration files
│ ├── env.py # Alembic environment configuration
│ ├── script.py.mako # Migration script template
├── logs/ # Application logs (created automatically)
├── .env.example # Environment variables template
├── .gitignore
├── alembic.ini # Alembic configuration
├── pyproject.toml # Poetry dependencies and configuration
└── README.md
- Python 3.11+
- PostgreSQL (or modify DATABASE_URL for your preferred database)
- Poetry (recommended) or pip
-
Clone the repository:
git clone <repository-url> cd fastapi-backend
-
Install dependencies:
# Using Poetry (recommended) poetry install # Or using pip pip install -r requirements.txt # If you generate requirements.txt
-
Set up environment variables:
cp .env.example .env # Edit .env with your configuration -
Configure the database:
- Create a PostgreSQL database
- Update
DATABASE_URLin your.envfile
-
Run database migrations:
# Using Poetry poetry run alembic upgrade head # Or using pip alembic upgrade head
# Using Poetry
poetry run uvicorn app.main:app --reload
# Or using pip
uvicorn app.main:app --reloadThe application will be available at http://localhost:8000
- Swagger UI:
http://localhost:8000/docs - ReDoc:
http://localhost:8000/redoc - OpenAPI Schema:
http://localhost:8000/api/v1/openapi.json
GET /api/v1/health- Health check with database connectivity
POST /api/v1/auth/login- Login and get access token
GET /- Basic API information
# Using Poetry
poetry run alembic revision --autogenerate -m "Description of changes"
# Or using pip
alembic revision --autogenerate -m "Description of changes"# Using Poetry
poetry run alembic upgrade head
# Or using pip
alembic upgrade head# Using Poetry
poetry run alembic downgrade -1
# Or using pip
alembic downgrade -1# Using Poetry
poetry run black .
poetry run isort .
# Or using pip
black .
isort .# Using Poetry
poetry run mypy .
# Or using pip
mypy .# Using Poetry
poetry run flake8 .
# Or using pip
flake8 .# Using Poetry
poetry run pytest
# Or using pip
pytestKey environment variables (see .env.example for complete list):
DATABASE_URL: Database connection stringSECRET_KEY: JWT secret key (change in production!)ALGORITHM: JWT algorithm (default: HS256)ACCESS_TOKEN_EXPIRE_MINUTES: Token expiration timeSMTP_*: Email configuration settingsDEBUG: Enable debug modeENVIRONMENT: Application environment (development/staging/production)
Add your SQLAlchemy model to app/models/:
# app/models/your_model.py
from sqlalchemy import Column, Integer, String
from app.core.database import Base
class YourModel(Base):
__tablename__ = "your_models"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False)Add repository logic to app/repositories/:
# app/repositories/your_model.py
from app.models.your_model import YourModel
from app.repositories.base import CRUDBase
class CRUDYourModel(CRUDBase[YourModel, Any, Any]):
pass
your_model = CRUDYourModel(YourModel)Add business logic to app/services/:
# app/services/your_model.py
from app.repositories.your_model import your_model
class YourModelService:
def __init__(self):
self.repo = your_model
def create_your_model(self, db, *, name: str):
return self.repo.create(db, obj_in={"name": name})
your_model_service = YourModelService()Add API routes to app/api/v1/:
# app/api/v1/your_model.py
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.services.your_model import your_model_service
router = APIRouter()
@router.post("/your-models")
def create_your_model(name: str, db: Session = Depends(get_db)):
return your_model_service.create_your_model(db=db, name=name)Add your router to app/api/v1/api.py:
from app.api.v1 import your_model
api_router.include_router(your_model.router, prefix="/your-models", tags=["your-model"])alembic revision --autogenerate -m "Add your model"
alembic upgrade head-
Security:
- Change
SECRET_KEYin production - Use HTTPS in production
- Set appropriate CORS origins
- Enable environment-specific configurations
- Change
-
Database:
- Use connection pooling
- Set appropriate database limits
- Regular backups
-
Logging:
- Configure log rotation
- Use structured logging for production
- Set appropriate log levels
-
Performance:
- Add database indexes
- Implement caching where needed
- Monitor application performance
- Follow the existing code style (Black + isort)
- Add tests for new features
- Update documentation
- Run type checking and linting before committing
Add your license information here.