### Local Development Setup Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Steps to clone the repository, set up a virtual environment, install dependencies, configure environment variables, initialize the database, and run the application locally. ```bash # 1. Clone the repository git clone https://github.com/Alwil17/fastapi-boilerplate.git cd fastapi-boilerplate # 2. Create virtual environment python -m venv . venv source .venv/bin/activate # Windows: .venv\Scripts\activate # 3. Install dependencies pip install -r requirements.txt pip install -r requirements-dev. txt # 4. Setup pre-commit hooks pre-commit install # 5. Configure environment cp .env.example .env # Edit .env with your configuration # 6. Initialize database alembic upgrade head # 7. Run the application uvicorn app.main:app --reload ``` -------------------------------- ### Docker Development Setup Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Instructions for cloning the repository and starting all services using Docker Compose for development. ```bash # 1. Clone the repository git clone https://github.com/Alwil17/fastapi-boilerplate. git cd fastapi-boilerplate # 2. Start all services docker-compose up -d # 3. View logs docker-compose logs -f api # 4. Access the API # http://localhost:8000 ``` -------------------------------- ### Run Development Server with Makefile Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Use 'make dev' to start the development server with auto-reloading enabled. Ensure dependencies are installed first with 'make install'. ```bash # Install all dependencies make install # Run development server with auto-reload make dev ``` -------------------------------- ### Install Dependencies Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/CONTRIBUTING.md Set up a virtual environment and install project dependencies using pip. ```bash python -m venv .venv source .venv/bin/activate # or .venv\Scripts\activate on Windows pip install -r requirements.txt ``` -------------------------------- ### Create and Apply Example Table Migration Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Bash commands to generate a new Alembic migration for the 'example' table and then apply it to the database. ```bash alembic revision --autogenerate -m "Add example table" alembic upgrade head ``` -------------------------------- ### Register Database Model Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Example of how to register a new database model ('Example') in the application's model initialization file. ```python # app/db/models/__init__.py from .user import User from .refresh_token import RefreshToken from .example import Example # Add new model __all__ = ["User", "RefreshToken", "Example"] ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/README.md Install all required Python packages listed in the requirements.txt file. ```bash pip install -r requirements.txt ``` -------------------------------- ### Set Up Environment Variables Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/README.md Copy the example environment file and edit it with your specific configurations. ```bash cp .env.example .env # Edit .env with your configuration ``` -------------------------------- ### Branch Naming Examples Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/CONTRIBUTING.md Examples of common branch naming conventions for features, bug fixes, chores, and documentation. ```bash git checkout -b feat/mood-analytics-endpoint ``` ```bash git checkout -b bugfix/fix-jwt-validation ``` ```bash git checkout -b feat/nlp-sentiment-analysis ``` -------------------------------- ### Install and Update Pre-commit Hooks Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Set up pre-commit hooks by running 'pre-commit install'. Update existing hooks to their latest versions using 'pre-commit autoupdate'. ```bash # Install hooks pre-commit install # Update hooks to latest versions pre-commit autoupdate ``` -------------------------------- ### Heroku Deployment Steps Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Instructions for deploying the application to Heroku, including CLI installation, login, app creation, add-ons, environment variables, deployment, and migrations. ```bash # Install Heroku CLI brew install heroku/brew/heroku # macOS # or download from https://devcenter.heroku.com/articles/heroku-cli # Login heroku login # Create app heroku create your-app-name # Add PostgreSQL heroku addons:create heroku-postgresql:hobby-dev # Set environment variables heroku config:set APP_SECRET_KEY=your-secret-key heroku config:set APP_ENV=production # Deploy git push heroku main # Run migrations heroku run alembic upgrade head # View logs heroku logs --tail ``` -------------------------------- ### User Registration Flow Example Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/ARCHITECTURE.md Illustrates the complete flow of a user registration request, from HTTP request to database interaction and response. This example requires Pydantic for DTOs and SQLAlchemy for database operations. ```python # 1. HTTP Request POST /auth/register { "name": "John Doe", "email": "john@example.com", "password": "securepass123" } # 2. Router receives and validates @router.post("/register", response_model=UserResponse) async def register(user_data: UserCreateDTO, db: Session = Depends(get_db)): # Pydantic validates input automatically # 3. Call service user_service = UserService(db) user = user_service.create_user(user_data) # 4. Return validated response return UserResponse.model_validate(user) # 5. Service applies business logic class UserService: def create_user(self, user_data: UserCreateDTO) -> User: # Check if user exists existing = self. user_repo.get_by_email(user_data.email) if existing: raise ValueError("Email already exists") # 6. Repository saves to database return self.user_repo.create(user_data) # 7. Repository interacts with database class UserRepository: def create(self, user_data: UserCreateDTO) -> User: user = User( name=user_data.name, email=user_data.email, hashed_password=hash_password(user_data.password) ) self.db.add(user) self.db.commit() self.db.refresh(user) return user # 8. HTTP Response { "id": 1, "name": "John Doe", "email": "john@example.com", "role": "user", "created_at": "2026-01-22T10:30:00Z", "updated_at": "2026-01-22T10:30:00Z" } ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/README.md Create a Python virtual environment to manage project dependencies. Activate it before installing packages. ```bash python -m venv . venv source .venv/bin/activate # On Windows: .venv\Scripts\activate ``` -------------------------------- ### Manage Docker Services with Makefile Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Start Docker services with 'make docker-up' and stop them with 'make docker-down'. ```bash # Start Docker services make docker-up # Stop Docker services make docker-down ``` -------------------------------- ### Verify API Installation Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Commands to check the API's health status and access the Swagger UI documentation. ```bash # Check API health curl http://localhost:8000/health # Access Swagger UI open http://localhost:8000/docs ``` -------------------------------- ### Dependency Injection Setup for Database Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/ARCHITECTURE.md Sets up a database session provider using FastAPI's dependency injection system. Ensures the session is closed after use. ```python # Dependency provider def get_db(): db = SessionLocal() try: yield db finally: db. close() ``` -------------------------------- ### Start FastAPI Development Server Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/README.md Run the FastAPI application using uvicorn. The --reload flag enables auto-reloading on code changes. ```bash uvicorn app.main:app --reload ``` -------------------------------- ### JWT Token Structure Example Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/ARCHITECTURE.md Demonstrates the typical structure of a JSON Web Token (JWT), including its header, payload, and signature components. ```text Header. Payload.Signature Header: { "alg": "HS256", "typ": "JWT" } Payload: { "sub": "user@example.com", "role": "user", "exp": 1706789000 } Signature: HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret_key ) ``` -------------------------------- ### Review Auto-Generated Migration Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Example of an auto-generated migration script for creating a 'users' table. Always review these operations before applying. ```python # alembic/versions/xxx_add_user_table.py def upgrade() -> None: # Review these operations op. create_table('users', sa.Column('id', sa.Integer(), nullable=False), sa.Column('email', sa.String(length=100), nullable=False), sa.PrimaryKeyConstraint('id') ) ``` -------------------------------- ### Define SQLAlchemy Database Model Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Example of a SQLAlchemy model definition for an 'Example' entity, including fields, foreign keys, timestamps, and relationships. ```python # app/db/models/example.py from datetime import datetime, timezone from sqlalchemy import Column, Integer, String, DateTime, ForeignKey from sqlalchemy.orm import relationship from app.db.models.base import Base class Example(Base): __tablename__ = "examples" # Primary key id = Column(Integer, primary_key=True, index=True) # Fields name = Column(String(100), nullable=False) description = Column(String(500)) # Foreign key user_id = Column(Integer, ForeignKey("users.id"), nullable=False) # Timestamps created_at = Column(DateTime, default=datetime.now(timezone.utc)) updated_at = Column( DateTime, default=datetime.now(timezone.utc), onupdate=datetime.now(timezone.utc), ) # Relationships user = relationship("User", back_populates="examples") def __repr__(self): return f"" ``` -------------------------------- ### Dependency Injection Usage in Route Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/ARCHITECTURE.md Demonstrates how to use dependency injection to get a UserService instance within a FastAPI route. Simplifies route logic. ```python # Usage in route @router.get("/users") async def list_users(service: UserService = Depends(get_user_service)): return service.list_users() ``` -------------------------------- ### Run Uvicorn on Different Port Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Start the Uvicorn server on a port other than the default. ```bash uvicorn app.main:app --port 8001 ``` -------------------------------- ### Environment Variables Configuration Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/README.md Example environment variables for configuring the FastAPI application, including application settings, database connection details, and JWT parameters. Refer to .env.example for a complete list. ```env # Application APP_NAME="FastAPI Boilerplate" APP_ENV=development APP_SECRET_KEY=your-secret-key # Database DB_ENGINE=postgresql DB_HOST=localhost DB_PORT=5432 DB_NAME=mydb DB_USER=user DB_PASSWORD=password # JWT ACCESS_TOKEN_EXPIRE_MINUTES=1440 REFRESH_TOKEN_EXPIRE_DAYS=7 ``` -------------------------------- ### Implement Rate Limiting with SlowAPI Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Set up rate limiting for API endpoints using the SlowAPI library. Requires installation via pip. ```python # Install slowapi pip install slowapi # Add to main.py from slowapi import Limiter, _rate_limit_exceeded_handler from slowapi.util import get_remote_address from slowapi.errors import RateLimitExceeded limiter = Limiter(key_func=get_remote_address) app.state.limiter = limiter app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) @router.post("/login") @limiter.limit("5/minute") async def login(request: Request, ... ): pass ``` -------------------------------- ### Get Current User with HTTPie Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Retrieve the current user's information using HTTPie. This requires a GET request to /auth/me with an Authorization header. ```bash # Get current user http GET localhost:8000/auth/me \ Authorization:"Bearer YOUR_TOKEN" ``` -------------------------------- ### Write Reversible Alembic Migration Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Example of a migration script that includes both an upgrade (adding a column) and a downgrade (dropping the column) operation. ```python def upgrade() -> None: op.add_column('users', sa.Column('phone', sa.String(20))) def downgrade() -> None: op. drop_column('users', 'phone') ``` -------------------------------- ### Implement Repository Pattern for Database Queries Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Python class implementing the repository pattern for CRUD operations on the 'Example' model using SQLAlchemy. ```python # app/repositories/example_repository.py from typing import List, Optional from sqlalchemy. orm import Session from app.db.models. example import Example class ExampleRepository: def __init__(self, db: Session): self.db = db def create(self, name: str, user_id: int) -> Example: example = Example(name=name, user_id=user_id) self.db.add(example) self.db.commit() self.db.refresh(example) return example def get_by_id(self, example_id: int) -> Optional[Example]: return self.db.query(Example).filter(Example.id == example_id).first() def get_all(self, skip: int = 0, limit: int = 100) -> List[Example]: return self. db.query(Example).offset(skip).limit(limit).all() def get_by_user(self, user_id: int) -> List[Example]: return self.db.query(Example).filter(Example.user_id == user_id).all() def update(self, example_id: int, name: str) -> Optional[Example]: example = self.get_by_id(example_id) if example: example.name = name self.db.commit() self.db.refresh(example) return example def delete(self, example_id: int) -> bool: example = self.get_by_id(example_id) if example: self.db.delete(example) self.db.commit() return True return False ``` -------------------------------- ### Test Get Current User Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Tests the protected '/auth/me' endpoint by first registering and logging in a user, then retrieving their information using a valid JWT token. ```python def test_get_current_user(client): """Test getting current user info with valid token.""" # Register and login client.post( "/auth/register", json={ "name": "Test User", "email": "test@example.com", "password": "password123" } ) login_response = client.post( "/auth/token", data={ "username": "test@example.com", "password": "password123" } ) token = login_response.json()["access_token"] # Get current user response = client.get( "/auth/me", headers={"Authorization": f"Bearer {token}"} ) assert response.status_code == 200 data = response.json() assert data["email"] == "test@example.com" ``` -------------------------------- ### Implement Prometheus Metrics Middleware Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/ARCHITECTURE.md Adds middleware to collect request counts and durations using Prometheus client. Ensure Prometheus client library is installed. ```python from prometheus_client import Counter, Histogram request_count = Counter('requests_total', 'Total requests') request_duration = Histogram('request_duration_seconds', 'Request duration') @app.middleware("http") async def metrics_middleware(request: Request, call_next): request_count.inc() with request_duration.time(): response = await call_next(request) return response ``` -------------------------------- ### Mocking External API Calls Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Demonstrates how to use `unittest.mock.patch` to mock external HTTP requests, allowing tests to run without actually calling external services. This example mocks a `requests.get` call. ```python from unittest.mock import Mock, patch def test_with_mock(client, mocker): """Test using mocked external service.""" # Mock external API call mock_response = Mock() mock_response.status_code = 200 mock_response.json.return_value = {"data": "mocked"} with patch('requests.get', return_value=mock_response): response = client.get("/external-api") assert response. status_code == 200 ``` -------------------------------- ### Show Makefile Commands Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Run 'make help' to display all available commands in the Makefile for managing dependencies, development server, code quality, testing, Docker, and database migrations. ```bash # Show all available commands make help ``` -------------------------------- ### Manage Pre-commit Hooks with Makefile Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Use 'make pre-commit-install' to set up pre-commit hooks and 'make pre-commit' to run them manually on all files. ```bash # Install pre-commit hooks make pre-commit-install # Run pre-commit hooks manually make pre-commit ``` -------------------------------- ### Get Current User with cURL Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Retrieve the current user's information by sending a GET request to the /auth/me endpoint. Requires an Authorization header with a Bearer token. ```bash # Get current user (requires authentication) curl -X GET "http://localhost:8000/auth/me" \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" ``` -------------------------------- ### Run Database Migrations Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/README.md Apply the latest database migrations to set up the database schema. ```bash alembic upgrade head ``` -------------------------------- ### Get Current User Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Retrieve information about the currently authenticated user. ```APIDOC ## GET /auth/me ### Description Retrieves the details of the currently authenticated user. ### Method GET ### Endpoint /auth/me ### Parameters #### Headers - **Authorization** (string) - Required - Bearer token for authentication (e.g., `Bearer YOUR_ACCESS_TOKEN`). ### Response #### Success Response (200) - **field1** (type) - Description (Details of the user object would be specified here if available in source). ``` -------------------------------- ### Manage Database Migrations with Makefile Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Apply database migrations using 'make migrate'. To create a new migration, use 'make migrate-create msg="description"'. ```bash # Apply database migrations make migrate # Create new migration make migrate-create msg="description" ``` -------------------------------- ### Docker Build and Run Commands Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Commands to build the Docker image, run the container, view logs, and stop the container. ```bash # Build image docker build -t fastapi-boilerplate: 1.0.0 . # Run container docker run -d \ --name fastapi-app \ -p 8000:8000 \ --env-file .env. production \ fastapi-boilerplate:1.0.0 # View logs docker logs -f fastapi-app # Stop container docker stop fastapi-app ``` -------------------------------- ### Build and Run Docker Image Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/README.md Build the Docker image for the FastAPI application and run it as a container, mapping the application port and loading environment variables from a .env file. ```bash # Build the image docker build -t fastapi-boilerplate . # Run the container docker run -p 8000:8000 --env-file .env fastapi-boilerplate ``` -------------------------------- ### Authentication Flow Diagram Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/ARCHITECTURE.md Illustrates the step-by-step process for user authentication, from registration to token generation and retrieval of user information. ```text ┌──────┐ ┌──────────┐ ┌──────────┐ │Client│ │ API │ │ DB │ └──┬───┘ └────┬─────┘ └────┬─────┘ │ │ │ │ POST /auth/register │ │ ├────────────────────────>│ │ │ {email, password} │ Save user │ │ ├──────────────────────────>│ │ │ │ │ │<──────────────────────────┤ │ 201 Created │ User created │ │<────────────────────────┤ │ │ │ │ │ POST /auth/token │ │ ├────────────────────────>│ │ │ {email, password} │ Verify credentials │ │ ├──────────────────────────>│ │ │ │ │ │<──────────────────────────┤ │ │ User found │ │ │ │ │ │ Create JWT + Refresh │ │ │◄──────────┐ │ │ │ │ │ │ │ │ │ │ {access_token, ... } │ Save refresh token │ │<────────────────────────┤──────────────────────────>│ │ │ │ │ GET /auth/me │ │ │ Authorization: Bearer │ │ ├────────────────────────>│ │ │ │ Validate JWT │ │ │◄──────────┐ │ │ │ │ │ │ │ Get user data │ │ ├──────────────────────────>│ │ │ │ │ │<──────────────────────────┤ │ {user_data} │ │ │<────────────────────────┤ │ │ │ │ ``` -------------------------------- ### Access ReDoc Documentation Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Access an alternative, clean documentation interface using ReDoc. It provides detailed schema information and code samples. ```text http://localhost:8000/redoc ``` -------------------------------- ### Run Tests with Makefile Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Execute 'make test' to run all tests and generate a coverage report. ```bash # Run tests with coverage make test ``` -------------------------------- ### Login with HTTPie Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Log in using HTTPie by sending a POST request to the /auth/token endpoint with username and password. ```bash # Login http POST localhost:8000/auth/token \ username=jane@example.com \ password=pass123 ``` -------------------------------- ### Run Code Quality Tools with Makefile Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Execute 'make lint' to run all linting tools (Ruff, MyPy), 'make format' to format code with Black and isort, and 'make security' for security checks (Bandit, Safety). ```bash # Run all linting tools (ruff, mypy) make lint # Format code with black and isort make format # Run security checks (bandit, safety) make security ``` -------------------------------- ### Run Tests Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/CONTRIBUTING.md Execute the test suite to ensure your changes do not break existing functionality. ```bash pytest ``` -------------------------------- ### Configure Python Logging Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/ARCHITECTURE.md Sets up basic logging configuration for the application. Use this to define the logging level and format. ```python import logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) @app.get("/users") async def list_users(): logger.info("Fetching users list") users = user_service.list_users() logger.info(f"Returned {len(users)} users") return users ``` -------------------------------- ### Clone the Repository Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/CONTRIBUTING.md Clone your forked repository to your local machine and navigate into the project directory. ```bash git clone https://github.com/YOUR_USERNAME/fastapi-boilerplate.git cd fastapi-boilerplate ``` -------------------------------- ### Check API Health with cURL Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Check the API's health status by sending a GET request to the /health endpoint. The response includes status, timestamp, database status, and version. ```bash # Check API health curl -X GET "http://localhost:8000/health" ``` -------------------------------- ### AWS ECS Deployment Overview Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md A high-level overview of the steps required for deploying to AWS Elastic Container Service (ECS). ```text 1. Create ECR repository 2. Build and push Docker image 3. Create ECS cluster 4. Define task definition 5. Create ECS service 6. Configure load balancer ``` -------------------------------- ### Register User with HTTPie Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Register a new user using HTTPie. This command sends a POST request to the /auth/register endpoint with specified user details. ```bash # Install HTTPie pip install httpie # Register user http POST localhost:8000/auth/register \ name="Jane Doe" \ email="jane@example.com" \ password="pass123" ``` -------------------------------- ### Optimize Database Queries with SQLAlchemy Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Demonstrates optimizing database queries using `select_related` for eager loading and `offset`/`limit` for pagination. Also shows how to add indexes. ```python # Use select_related to avoid N+1 queries users = db.query(User).options(joinedload(User.refresh_tokens)).all() # Use pagination users = db.query(User).offset(skip).limit(limit).all() # Add database indexes class User(Base): email = Column(String, unique=True, index=True) ``` -------------------------------- ### Create Database Migration Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Generate and apply a new database migration using Alembic. ```bash alembic revision --autogenerate -m "Add feature table" alembic upgrade head ``` -------------------------------- ### Force Downgrade and Upgrade Migrations Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md In critical situations, downgrade to the base revision and then upgrade to the latest. Use with extreme caution. ```bash alembic downgrade base alembic upgrade head ``` -------------------------------- ### Create Routes Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Set up API routes for a new feature using FastAPI's APIRouter. ```python # app/api/routes/feature_routes.py router = APIRouter(prefix="/features", tags=["Features"]) # Define endpoints ``` -------------------------------- ### Register a New User with cURL Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Register a new user by sending a POST request to the /auth/register endpoint with JSON payload. ```bash # Register a new user curl -X POST "http://localhost:8000/auth/register" \ -H "Content-Type: application/json" \ -d '{ "name": "John Doe", "email": "john@example.com", "password": "securepass123" }' ``` -------------------------------- ### Run Pytest from Project Root Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Navigate to the project root and run pytest using the -m flag. ```bash cd /path/to/fastapi-boilerplate python -m pytest ``` -------------------------------- ### SQLAlchemy Query Optimization Techniques Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/ARCHITECTURE.md Demonstrates techniques to optimize database queries using SQLAlchemy, including avoiding N+1 queries with joinedload, implementing pagination with offset/limit, and selecting specific columns. ```python # Avoid N+1 queries users = db.query(User).options( joinedload(User.refresh_tokens) ).all() # Use pagination users = db. query(User).offset(skip).limit(limit).all() # Use select specific columns users = db.query(User. id, User.email).all() ``` -------------------------------- ### Type Hinting Best Practices in Python Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Demonstrates the correct usage of type hints for function parameters, return values, and variables in Python to improve code clarity and enable static analysis. ```python # Good: Type hints for function parameters and return def get_user(user_id: int) -> Optional[User]: return db.query(User).filter(User.id == user_id).first() # Good: Type hints for variables name: str = "John" age: int = 30 ``` -------------------------------- ### Concrete Repository Implementation Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/ARCHITECTURE.md Provides a concrete implementation of the repository interface for database interactions. Requires a database session. ```python class UserRepository(IUserRepository): def __init__(self, db: Session): self.db = db def create(self, user_data: UserCreateDTO) -> User: # Implementation pass ``` -------------------------------- ### User Registration Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Register a new user by providing their name, email, and password. ```APIDOC ## POST /auth/register ### Description Registers a new user. ### Method POST ### Endpoint /auth/register ### Parameters #### Request Body - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email address of the user. - **password** (string) - Required - The password for the user account. ### Request Example ```json { "name": "John Doe", "email": "john@example.com", "password": "securepass123" } ``` ``` -------------------------------- ### Alembic Migration Commands Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/ARCHITECTURE.md Provides commands for creating and applying database migrations using Alembic. ```bash # Create migration alembic revision --autogenerate -m "add column" # Apply migration alembic upgrade head ``` ```bash # Test migration alembic upgrade head # Verify data integrity # Run tests # Rollback if needed alembic downgrade -1 ``` ```bash # Backup database pg_dump database > backup.sql # Apply migration alembic upgrade head # Monitor for issues # Rollback if critical issues ``` -------------------------------- ### Check Database Environment Variables Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md View database-related environment variables by grepping the .env file. ```bash cat .env | grep DB_ ``` -------------------------------- ### Downgrade and Upgrade Migrations Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Perform a downgrade by one revision and then upgrade to the latest version using Alembic. ```bash alembic downgrade -1 alembic upgrade head ``` -------------------------------- ### Google Cloud Run Deployment Commands Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Commands to build and push a Docker image to Google Container Registry (GCR) and deploy it to Google Cloud Run. ```bash # Build and push image gcloud builds submit --tag gcr.io/PROJECT_ID/fastapi-boilerplate # Deploy gcloud run deploy fastapi-boilerplate \ --image gcr.io/PROJECT_ID/fastapi-boilerplate \ --platform managed \ --region us-central1 \ --allow-unauthenticated ``` -------------------------------- ### Clone FastAPI Boilerplate Repository Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/README.md Use this command to clone the project repository. Navigate into the cloned directory afterwards. ```bash git clone https://github.com/Alwil17/fastapi-boilerplate.git cd fastapi-boilerplate ``` -------------------------------- ### Login and Obtain Token with cURL Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Log in to obtain an access token and refresh token by sending a POST request to the /auth/token endpoint with form-urlencoded data. ```bash # Login curl -X POST "http://localhost:8000/auth/token" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "username=john@example.com&password=securepass123" ``` -------------------------------- ### Commit and Push Changes Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/CONTRIBUTING.md Stage, commit, and push your changes to your fork's branch. ```bash git add . git commit -m "Describe your change" git push origin my-feature ``` -------------------------------- ### Create Repository Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Implement a repository class to handle CRUD operations for a new feature. ```python # app/repositories/feature_repository.py class FeatureRepository: # Define CRUD operations ``` -------------------------------- ### Write Tests Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Write a test case for creating a new feature using a FastAPI test client. ```python # tests/test_feature. py def test_create_feature(client): # Test implementation ``` -------------------------------- ### View PostgreSQL Logs Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Use docker-compose to view the logs for the PostgreSQL database service. ```bash docker-compose logs db ``` -------------------------------- ### View Alembic Current Version Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Check the current version of your database migrations using Alembic. ```bash alembic current ``` -------------------------------- ### Reinstall Dependencies Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Force reinstall all project dependencies using pip. ```bash pip install -r requirements.txt --force-reinstall ``` -------------------------------- ### Create Service Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Define a service class to encapsulate business logic for a new feature. ```python # app/services/feature_service.py class FeatureService: # Define business logic ``` -------------------------------- ### Apply Alembic Migrations Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Commands to apply database migrations, including upgrading to the latest version, specific versions, or downgrading. ```bash # Upgrade to latest alembic upgrade head ``` ```bash # Upgrade one version alembic upgrade +1 ``` ```bash # Downgrade one version alembic downgrade -1 ``` ```bash # Downgrade to specific version alembic downgrade ``` ```bash # Downgrade all alembic downgrade base ``` -------------------------------- ### Reinstall Pre-commit Hooks Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Uninstall and then reinstall pre-commit hooks for the current repository. ```bash pre-commit uninstall pre-commit install ``` -------------------------------- ### Utilize Async Operations for I/O Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Perform asynchronous database queries using `async` and `await` for non-blocking I/O operations. ```python # Use async for I/O operations @router.get("/users") async def get_users(): # Async database query users = await db.execute(select(User)) return users ``` -------------------------------- ### Service Factory Implementation Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/ARCHITECTURE.md A static factory class for creating service instances. Centralizes object creation logic for different services. ```python class ServiceFactory: @staticmethod def create_user_service(db: Session) -> UserService: return UserService(db) @staticmethod def create_auth_service(db: Session) -> AuthService: return AuthService(db) ``` -------------------------------- ### Run Tests with Pytest Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/README.md Execute tests using Pytest. Options include running all tests, running tests with code coverage, and running a specific test file. ```bash # Run all tests pytest # Run with coverage pytest --cov=app tests/ # Run specific test file pytest tests/test_auth.py -v ``` -------------------------------- ### User Login Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Log in a user by providing their email and password to obtain authentication tokens. ```APIDOC ## POST /auth/token ### Description Logs in a user and returns access and refresh tokens. ### Method POST ### Endpoint /auth/token ### Parameters #### Request Body - **username** (string) - Required - The user's email address. - **password** (string) - Required - The user's password. ### Request Example ``` username=john@example.com&password=securepass123 ``` ### Response #### Success Response (200) - **access_token** (string) - The JWT access token. - **refresh_token** (string) - The JWT refresh token. - **token_type** (string) - The type of token, typically 'bearer'. ### Response Example ```json { "access_token": "eyJ0eXAiOiJKV1QiLCJhbGc...", "refresh_token": "a1b2c3d4...", "token_type": "bearer" } ``` ``` -------------------------------- ### Basic Test Structure Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Demonstrates the standard structure for a FastAPI test function, including arranging test data, acting by calling the client, and asserting the expected outcomes. ```python # tests/test_example.py def test_function_name(client, db_session): """Test description of what is being tested.""" # Arrange - Setup test data user_data = { "name": "Test User", "email": "test@example.com", "password": "password123" } # Act - Execute the code being tested response = client.post("/auth/register", json=user_data) # Assert - Verify the results assert response.status_code == 201 assert response. json()["email"] == user_data["email"] ``` -------------------------------- ### Development Environment Variables Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Configuration for the development environment. Ensure sensitive keys are changed for production. ```env APP_NAME="FastAPI Boilerplate Dev" APP_ENV=development APP_DEBUG=True APP_SECRET_KEY=dev-secret-key-change-in-production DB_ENGINE=postgresql DB_HOST=localhost DB_PORT=5432 DB_NAME=mydb_dev DB_USER=dev_user DB_PASSWORD=dev_password ACCESS_TOKEN_EXPIRE_MINUTES=1440 REFRESH_TOKEN_EXPIRE_DAYS=7 ``` -------------------------------- ### Test Alembic Migrations Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Commands to test migration scripts in a development environment by applying and downgrading. ```bash # Test upgrade alembic upgrade head # Test downgrade alembic downgrade -1 # Test upgrade again alembic upgrade head ``` -------------------------------- ### Clean Cache Files with Makefile Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Remove cache files from the project using the 'make clean' command. ```bash # Remove cache files make clean ``` -------------------------------- ### Download OpenAPI Specification Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Download the OpenAPI specification in JSON format. This file describes the API's structure and endpoints. ```text http://localhost:8000/openapi.json ``` -------------------------------- ### Python Integration Test for User Repository Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/ARCHITECTURE.md Tests the creation of a user via the repository layer and verifies its persistence in the database. ```python def test_user_repository_create(db_session): """Test repository creates user in database""" repo = UserRepository(db_session) user_data = UserCreateDTO( name="Test User", email="test@example.com", password="password123" ) user = repo.create(user_data) assert user.id is not None assert user.email == user_data.email # Verify in database db_user = db_session.query(User).filter(User.id == user.id).first() assert db_user is not None ``` -------------------------------- ### Production Environment Variables Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Configuration for the production environment. Emphasizes security and production-specific settings. ```env APP_NAME="FastAPI Boilerplate" APP_ENV=production APP_DEBUG=False APP_SECRET_KEY=your-super-secure-secret-key-min-32-chars DB_ENGINE=postgresql DB_HOST=your-production-db-host. com DB_PORT=5432 DB_NAME=prod_database DB_USER=prod_user DB_PASSWORD=very-secure-production-password ACCESS_TOKEN_EXPIRE_MINUTES=60 REFRESH_TOKEN_EXPIRE_DAYS=7 ``` -------------------------------- ### Database Connection Pooling Configuration Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/ARCHITECTURE.md Configures SQLAlchemy's create_engine with connection pooling parameters. Sets the pool size, maximum overflow, and enables pre-ping for connection health checks. ```python engine = create_engine( DATABASE_URL, pool_size=10, max_overflow=20, pool_pre_ping=True ) ``` -------------------------------- ### Access Swagger UI Documentation Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Access the interactive API documentation through Swagger UI. This interface allows you to try out API endpoints, view schemas, and test authentication. ```text http://localhost:8000/docs ``` -------------------------------- ### Database and Client Fixtures Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Provides essential pytest fixtures for setting up a test database session and a test client for FastAPI applications. These fixtures manage database connections and dependency overrides. ```python # tests/conftest.py import pytest from fastapi.testclient import TestClient from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker @pytest.fixture def db_session(): """Create a test database session.""" engine = create_engine("sqlite:///:memory:") TestingSessionLocal = sessionmaker(bind=engine) db = TestingSessionLocal() try: yield db finally: db.close() ``` ```python @pytest.fixture def client(db_session): """Create a test client.""" from app.main import app from app.db.base import get_db def override_get_db(): try: yield db_session finally: pass app.dependency_overrides[get_db] = override_get_db yield TestClient(app) app.dependency_overrides.clear() ``` -------------------------------- ### View Alembic Migration History Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Commands to inspect the current database version and view the history and details of applied migrations. ```bash # Show current version alembic current ``` ```bash # Show migration history alembic history ``` ```bash # Show migration details alembic show ``` -------------------------------- ### Create a New Branch Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/CONTRIBUTING.md Create a new branch for your feature or bug fix before making changes. ```bash git checkout -b my-feature ``` -------------------------------- ### Optimized Dockerfile for Production Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md A multi-stage Dockerfile designed for smaller production images by separating build dependencies from the final runtime environment. ```dockerfile # Multi-stage build for smaller image FROM python:3.11-slim as builder WORKDIR /app # Install dependencies COPY requirements.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /app/wheels -r requirements.txt # Final stage FROM python:3.11-slim WORKDIR /app # Copy wheels from builder COPY --from=builder /app/wheels /wheels COPY --from=builder /app/requirements.txt . # Install dependencies RUN pip install --no-cache /wheels/* # Copy application COPY ./app ./app COPY ./alembic ./alembic COPY ./alembic.ini . # Create non-root user RUN useradd -m -u 1000 appuser && chown -R appuser:appuser /app USER appuser # Expose port EXPOSE 8000 # Run application CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"] ``` -------------------------------- ### Write Docstrings for Python Functions Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Document Python functions using docstrings to explain their purpose, arguments, return values, and potential exceptions. ```python def create_user(user_data: UserCreateDTO) -> User: """ Create a new user in the database. Args: user_data: User creation data including name, email, and password Returns: User: The created user object Raises: ValueError: If user with email already exists """ pass ``` -------------------------------- ### Auth Service with Strategy Pattern Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/ARCHITECTURE.md Uses a strategy pattern to perform authentication. Allows switching between different authentication methods (e.g., Email/Password, OAuth2) without changing the service's core logic. ```python class AuthService: def __init__(self, strategy: AuthenticationStrategy): self.strategy = strategy def login(self, credentials: dict) -> Optional[User]: return self.strategy.authenticate(credentials) ``` -------------------------------- ### User Repository Implementation in Python Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/ARCHITECTURE.md Handles CRUD operations and database interactions for the User model. Requires a SQLAlchemy Session object for database access. ```python # app/repositories/user_repository.py from typing import List, Optional from sqlalchemy.orm import Session from app.db. models.user import User from app.schemas.user_dto import UserCreateDTO, UserUpdateDTO from app.core.security import hash_password class UserRepository: """User data access layer""" def __init__(self, db: Session): self.db = db def create(self, user_data: UserCreateDTO) -> User: """Insert new user into database""" user = User( name=user_data.name, email=user_data.email, hashed_password=hash_password(user_data.password) ) self.db.add(user) self.db.commit() self.db.refresh(user) return user def get_by_id(self, user_id: int) -> Optional[User]: """Get user by ID""" return self.db.query(User).filter(User.id == user_id).first() def get_by_email(self, email: str) -> Optional[User]: """Get user by email""" return self. db.query(User).filter(User.email == email).first() def list(self, skip: int = 0, limit: int = 100) -> List[User]: """List users with pagination""" return self.db.query(User).offset(skip).limit(limit).all() def update(self, user_id: int, user_data: UserUpdateDTO) -> Optional[User]: """Update existing user""" user = self. get_by_id(user_id) if not user: return None update_data = user_data.model_dump(exclude_unset=True) if "password" in update_data: update_data["hashed_password"] = hash_password(update_data. pop("password")) for key, value in update_data. items(): setattr(user, key, value) self.db.commit() self.db.refresh(user) return user def delete(self, user_id: int) -> bool: """Delete user by ID""" user = self.get_by_id(user_id) if not user: return False self.db.delete(user) self.db.commit() return True ``` -------------------------------- ### Docker Compose Production Configuration Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Defines services for database, API, and Nginx for a production environment using Docker Compose. ```yaml version: '3.8' services: db: image: postgres:16-alpine environment: POSTGRES_DB: ${DB_NAME} POSTGRES_USER: ${DB_USER} POSTGRES_PASSWORD: ${DB_PASSWORD} volumes: - postgres_data:/var/lib/postgresql/data restart: unless-stopped healthcheck: test: ["CMD-SHELL", "pg_isready -U ${DB_USER}"] interval: 10s timeout: 5s retries: 5 api: build: . ports: - "8000:8000" env_file: - .env.production depends_on: db: condition: service_healthy restart: unless-stopped healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8000/health"] interval: 30s timeout: 10s retries: 3 nginx: image: nginx:alpine ports: - "80:80" - "443:443" volumes: - ./nginx. conf:/etc/nginx/nginx. conf: ro - ./ssl:/etc/nginx/ssl:ro depends_on: - api restart: unless-stopped volumes: postgres_data: ``` -------------------------------- ### Create Database Model Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Define a database model for a new feature using SQLAlchemy. ```python # app/db/models/feature.py class Feature(Base): __tablename__ = "features" # Define columns ``` -------------------------------- ### Run Pre-commit Hooks Manually Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Execute pre-commit hooks manually on all files with 'pre-commit run --all-files'. You can also run a specific hook, like 'black', using 'pre-commit run black --all-files'. ```bash # Run manually on all files pre-commit run --all-files # Run specific hook pre-commit run black --all-files ``` -------------------------------- ### Test User Registration Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Tests the user registration endpoint to ensure a new user can be created successfully and returns the correct status code and email. ```python def test_register_user(client): """Test user registration creates a new user.""" response = client.post( "/auth/register", json={ "name": "John Doe", "email": "john@example.com", "password": "securepass123" } ) assert response.status_code == 201 data = response.json() assert data["email"] == "john@example.com" assert "id" in data assert "hashed_password" not in data # Password should not be returned ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/alwil17/fastapi-boilerplate/blob/master/docs/USAGE_GUIDE.md Configure Python's logging module to display DEBUG level messages and above. This snippet should be placed in app/main.py. ```python # app/main.py import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) @app.get("/debug") async def debug(): logger.debug("Debug information") logger.info("Info message") logger.warning("Warning message") logger.error("Error message") return {"debug": "enabled"} ```