### Copy Example Environment File Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/configuration.md Copy the example environment file to start configuring your application. This sets up the initial configuration structure. ```bash cd backend cp .env.example .env ``` -------------------------------- ### Quick Start with uv Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/index.md Clone the repository, navigate to the backend directory, install development dependencies with uv, configure environment variables, and run the development server. ```bash git clone https://github.com/benavlabs/fastapi-boilerplate cd fastapi-boilerplate/backend uv sync --extra dev cp .env.example .env # then edit values as needed uv run fastapi dev src/interfaces/main.py ``` -------------------------------- ### Example .env File Variables Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/configuration/index.md Essential variables for application, database, and admin account setup. ```env # Application APP_NAME=My FastAPI App SECRET_KEY=your-super-secret-key-here # Database POSTGRES_USER=your_user POSTGRES_PASSWORD=your_password POSTGRES_DB=your_database # Admin Account (used by setup_initial_data) ADMIN_NAME=Admin User ADMIN_EMAIL=admin@example.com ADMIN_USERNAME=admin ADMIN_PASSWORD=secure_password ``` -------------------------------- ### Install and Use a Command Plugin Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/cli/plugins.md Install the command plugin using `uv pip` and then use the new command via `uv run bp`. The example shows how to verify the new command is available and how to execute it. ```bash uv pip install bp-deploy-fly uv run bp --help # ╭─ Commands ────────────────────────────────────────────────╮ # │ deploy Generate deployment artifacts ... │ # │ env Inspect and prepare the runtime environment. │ # │ fly Deploy this app to Fly.io. ← new │ # ╰───────────────────────────────────────────────────────────╯ uv run bp fly deploy --region ord --yes ``` -------------------------------- ### Quick Start with Docker Compose Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/index.md Clone the repository, navigate to the backend directory, and start the services using Docker Compose. ```bash git clone https://github.com/benavlabs/fastapi-boilerplate cd fastapi-boilerplate/backend docker compose up ``` -------------------------------- ### Example .env File Configuration Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/configuration/index.md Example of environment variables for database and application settings. ```env POSTGRES_USER=myuser POSTGRES_PASSWORD=mypassword CACHE_REDIS_HOST=localhost SECRET_KEY=your-secret-key ``` -------------------------------- ### Execute Initial Setup Command Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/configuration/docker-setup.md Command to run the initial setup job in a temporary container. ```bash docker compose run --rm setup ``` -------------------------------- ### Install Dependencies with uv Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/CONTRIBUTING.md Navigate to the cloned repository and install project dependencies using uv. ```sh cd FastAPI-boilerplate uv sync ``` -------------------------------- ### Set Up Environment File Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/installation.md Copy the example environment file to create your local environment configuration. ```bash cp backend/.env.example backend/.env ``` -------------------------------- ### Quick Start Docker Compose Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/configuration/docker-setup.md Navigate to the backend directory, copy the environment file, edit it with necessary configurations, and then start the services using Docker Compose. ```bash cd backend cp .env.example .env # edit .env (set SECRET_KEY, change default DB password, etc.) docker compose up ``` -------------------------------- ### Install uv via Script Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/installation.md Install the uv Python package manager using the provided installation script for macOS and Linux. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Set Up Environment File Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/installation.md Copy the example environment file and edit it to configure your application settings. ```bash cp .env.example .env # Edit .env: set SECRET_KEY, change default DB password, etc. ``` -------------------------------- ### Clone Repository for Manual Installation Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/installation.md Clone the repository for manual installation and navigate to the root directory. ```bash git clone https://github.com/benavlabs/fastapi-boilerplate cd fastapi-boilerplate ``` -------------------------------- ### Setup Initial Data Script Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/configuration.md Run the script to set up initial data, including the first admin user. This command executes the setup process defined in the scripts. ```bash uv run python -m scripts.setup_initial_data ``` -------------------------------- ### Install Redis on Ubuntu/Debian Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/installation.md Install the Redis server on Ubuntu or Debian systems. ```bash sudo apt install redis-server ``` -------------------------------- ### Install PostgreSQL on Ubuntu/Debian Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/installation.md Install PostgreSQL server and contrib packages on Ubuntu or Debian systems. ```bash sudo apt install postgresql postgresql-contrib ``` -------------------------------- ### Install Redis on macOS Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/installation.md Install Redis on macOS using Homebrew. ```bash brew install redis ``` -------------------------------- ### Set Up Environment Variables Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/configuration/index.md Copy the example .env file and edit it to set essential application, database, and admin account variables. ```bash cd backend cp .env.example .env $EDITOR .env ``` -------------------------------- ### Clone and Navigate Project (Bash) Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/index.md Clone the repository and navigate to the backend directory to begin setup. ```bash git clone https://github.com/yourusername/your-project-name cd your-project-name/backend ``` -------------------------------- ### Install uv via pip Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/installation.md Install the uv Python package manager using pip. ```bash pip install uv ``` -------------------------------- ### Install bp machine-wide Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/cli/README.md Install the bp CLI globally for machine-wide access. This allows you to run `bp` commands from any directory. ```bash uv tool install --editable ./cli bp --help ``` -------------------------------- ### Install PostgreSQL on macOS Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/installation.md Install PostgreSQL on macOS using Homebrew. ```bash brew install postgresql ``` -------------------------------- ### Install and Use Feature Plugin Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/cli/plugins.md Commands for installing the feature plugin using `uv pip` and a hypothetical future command for adding the feature to a project. ```bash uv pip install bp-feature-audit-log # Once `bp feature` ships: # uv run bp feature add audit-log --retention-days 90 ``` -------------------------------- ### Install Dependencies with uv (Bash) Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/index.md Install project dependencies, including development extras, using the uv package manager. ```bash uv sync --extra dev ``` -------------------------------- ### Set Up Pre-commit Hooks Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/installation.md Install pre-commit hooks to ensure code quality and consistency. Run this command from the repository root. ```bash uv run --project backend pre-commit install ``` -------------------------------- ### Start Application with Docker Compose Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/README.md Builds and starts the application using Docker Compose. Access the API at http://127.0.0.1:8000, with Swagger UI available at /docs. ```bash docker compose up --build ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/installation.md Clone the repository and navigate to the backend directory for Docker Compose setup. ```bash git clone https://github.com/benavlabs/fastapi-boilerplate cd fastapi-boilerplate/backend ``` -------------------------------- ### Initial Setup Job Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/configuration/docker-setup.md This service creates the first admin user and default tier on a fresh database. It depends on the `db` service. ```yaml setup: build: context: . dockerfile: Dockerfile target: dev env_file: - .env command: python -m scripts.setup_initial_data depends_on: - db ``` -------------------------------- ### Copy Environment File (Bash) Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/index.md Copy the example environment file to .env and edit it to configure your database credentials, SECRET_KEY, and other settings. ```bash cp .env.example .env # then edit .env to set your database creds, SECRET_KEY, etc. ``` -------------------------------- ### Install Python Dependencies with uv Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/installation.md Install all Python dependencies for the workspace, including backend, CLI, and dev tools, using uv. ```bash uv sync --all-packages --all-extras ``` -------------------------------- ### Install Boilerplate as Global Tool Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/README.md Optionally install the FastAPI boilerplate as a global tool for easier access to its CLI commands. ```bash # install bp as a global tool (optional) uv tool install --editable ./cli ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/CONTRIBUTING.md Install pre-commit hooks into your local Git repository to automatically check code quality before commits. ```sh pre-commit install ``` -------------------------------- ### Install bp CLI In-Repo Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/cli/index.md Clone the repository, sync dependencies using uv, and run the bp CLI from anywhere within the repo. ```bash git clone https://github.com/benavlabs/fastapi-boilerplate cd fastapi-boilerplate uv sync # syncs the workspace; installs backend + cli into one venv uv run bp --help # works from anywhere in the repo ``` -------------------------------- ### Run Development Server with uv (Bash) Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/index.md Start the FastAPI development server using uv. Ensure you have the main application file path correct. ```bash uv run fastapi dev src/interfaces/main.py ``` -------------------------------- ### Install bp within the workspace Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/cli/README.md Sync the workspace and then run the bp CLI using `uv run`. This is the recommended method when working within the project repository. ```bash uv sync # syncs the workspace; bp is available via `uv run bp` uv run bp --help ``` -------------------------------- ### Install Taskiq RabbitMQ Broker Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/background-tasks/index.md Install the optional 'taskiq-aio-pika' package if you are using RabbitMQ as your broker. The boilerplate includes this dependency, but the import is conditional. ```bash uv add taskiq-aio-pika ``` -------------------------------- ### Start Services with Docker Compose (Bash) Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/index.md Launch the FastAPI application, PostgreSQL, and Redis services using Docker Compose. This command brings up all necessary components for development. ```bash docker compose up ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/README.md Copies the example environment file and generates a new secret key. Use 'validate' to audit your .env file against production requirements. ```bash cp backend/.env.example backend/.env ``` ```bash uv run bp env gen-secret ``` ```bash uv run bp env validate ``` -------------------------------- ### Production .env Configuration Example Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/production.md This is a bare-minimum configuration for a production environment. Ensure secrets like SECRET_KEY, POSTGRES_PASSWORD, and cache/session/taskiq passwords are generated and unique. ```env ENVIRONMENT=production DEBUG=false APP_NAME="Your Production App" VERSION=1.0.0 SECRET_KEY= POSTGRES_USER=app_prod POSTGRES_PASSWORD= POSTGRES_SERVER= POSTGRES_PORT=5432 POSTGRES_DB=app_prod CREATE_TABLES_ON_STARTUP=false CONFIRM_PRODUCTION_MIGRATION=yes CORS_ORIGINS=["https://app.example.com","https://admin.example.com"] CACHE_ENABLED=true CACHE_BACKEND=redis CACHE_REDIS_HOST= CACHE_REDIS_PASSWORD= SESSION_BACKEND=redis SESSION_REDIS_HOST= SESSION_REDIS_PASSWORD= SESSION_SECURE_COOKIES=true CSRF_ENABLED=true TRUSTED_PROXY_HOPS=1 RATE_LIMITER_ENABLED=true RATE_LIMITER_BACKEND=redis RATE_LIMITER_REDIS_HOST= RATE_LIMITER_REDIS_PASSWORD= RATE_LIMITER_FAIL_OPEN=true TASKIQ_ENABLED=true TASKIQ_BROKER_TYPE=redis TASKIQ_REDIS_HOST= TASKIQ_REDIS_PASSWORD= ADMIN_ENABLED=false ADMIN_USERNAME= ADMIN_PASSWORD= OPENAPI_URL= LOG_LEVEL=INFO LOG_FORMAT=json ``` -------------------------------- ### List In-tree and Plugin Commands Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/cli/plugins.md Use this command to list all available commands, including those provided by installed plugins. This helps in discovering the CLI's capabilities. ```bash # In-tree + plugin commands uv run bp --help ``` ```bash # (Once shipped) — list features: # uv run bp feature list ``` -------------------------------- ### SQL Migration for Seeding Rate Limits Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/rate-limiting/index.md An example of an Alembic migration script to insert initial rate limit rules directly into the database using SQL. ```python # alembic/versions/xxxx_seed_rate_limits.py def upgrade(): op.execute(""" INSERT INTO rate_limits (tier_id, name, path, "limit", period, created_at) VALUES (1, 'free_widgets_create', 'api_v1_widgets', 10, 60, NOW()), (2, 'pro_widgets_create', 'api_v1_widgets', 100, 60, NOW()) """) ``` -------------------------------- ### Install Python 3.11 on macOS Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/installation.md Install Python 3.11 on macOS using Homebrew. ```bash brew install python@3.11 ``` -------------------------------- ### Production Dockerfile CMD Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/production.md The default command for the production Docker image uses `fastapi run` to start the application. It binds to all interfaces and specifies the application entry point. ```dockerfile CMD ["sh", "-c", "fastapi run interfaces/main.py --host 0.0.0.0 --port 8000 --workers $WORKERS"] ``` -------------------------------- ### Install Python 3.11 on Ubuntu/Debian Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/installation.md Install Python 3.11 on Ubuntu or Debian systems. ```bash sudo apt update && sudo apt install python3.11 ``` -------------------------------- ### Set up PostgreSQL Database and User Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/installation.md Create a new database and user in PostgreSQL, granting necessary privileges. ```sql sudo -u postgres psql CREATE DATABASE myapp; CREATE USER myuser WITH PASSWORD 'mypassword'; GRANT ALL PRIVILEGES ON DATABASE myapp TO myuser; \q ``` -------------------------------- ### Run Backend Migrations and Setup Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/README.md Applies database migrations and sets up initial data, including the first admin user and default tier. Requires Postgres and Redis to be running locally. ```bash uv run alembic upgrade head ``` ```bash uv run python -m scripts.setup_initial_data ``` -------------------------------- ### Start a Taskiq Worker Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/installation.md Start a Taskiq worker in a separate terminal to process background tasks. ```bash uv run taskiq worker infrastructure.taskiq.worker:default_broker ``` -------------------------------- ### Create Admin User and Default Tier Locally Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/first-run.md Execute the initial data setup script locally using uv to create the admin user and default tier. Ensure you are in the 'backend' directory. ```bash cd backend uv run python -m scripts.setup_initial_data ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/installation.md Fork the repository on GitHub first, then clone it and navigate into the project directory. ```bash # Fork on GitHub first git clone https://github.com/yourusername/fastapi-boilerplate cd fastapi-boilerplate ``` -------------------------------- ### Configuration Files Overview Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/project-structure.md Explanation of key configuration files and their purposes. ```markdown | File | Purpose | |------|---------| | `pyproject.toml` | Project metadata, dependencies (`[project]`), tooling config (ruff, mypy, pytest) | | `uv.lock` | Locks exact dependency versions for reproducible installs | | `Dockerfile` | Multi-stage build: requirements export → base → dev/prod/migrate stages | | `alembic.ini` | Alembic settings (script location, logging) | | `.env.example` | Documented reference of every environment variable | ``` -------------------------------- ### Get Single Item Endpoint Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/api/endpoints.md Defines a GET endpoint to retrieve a single item by its ID. Handles not found errors and general exceptions. ```python from fastapi import Depends, HTTPException from sqlalchemy.ext.asyncio import AsyncSession from typing import Any from app.db.session import async_session from app.services.widget_service import WidgetService, get_widget_service from app.models.widget import WidgetRead from app.utils.exception_handler import handle_exception from fastapi import APIRouter router = APIRouter() @router.get("/{widget_id}", response_model=WidgetRead) async def get_widget( widget_id: int, db: Annotated[AsyncSession, Depends(async_session)], widget_service: Annotated[WidgetService, Depends(get_widget_service)], ) -> dict[str, Any]: try: widget = await widget_service.get_by_id(widget_id, db) if widget is None: raise HTTPException(status_code=404, detail=f"Widget {widget_id} not found") return widget except Exception as e: http_exc = handle_exception(e) if http_exc: raise http_exc raise HTTPException(status_code=500, detail="An unexpected error occurred") ``` -------------------------------- ### Production CORS Configuration Example Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/configuration.md Example of secure CORS configuration for production environments. It specifies exact origins, allowed methods, and headers to enhance security. ```env CORS_ORIGINS=https://yourapp.com,https://www.yourapp.com CORS_ALLOW_METHODS=GET,POST,PUT,DELETE,PATCH CORS_ALLOW_HEADERS=Authorization,Content-Type ``` -------------------------------- ### Development Environment Configuration Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/admin-panel/configuration.md Example .env file for development. Sets environment to development, enables the admin panel, and provides default admin credentials. The SECRET_KEY is insecure and must be changed for production. ```env ENVIRONMENT=development ADMIN_ENABLED=true ADMIN_USERNAME=admin ADMIN_PASSWORD=your-secure-password SECRET_KEY=insecure-secret-key-change-this-in-production ``` -------------------------------- ### Get Multiple Items (Paginated) Endpoint Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/api/endpoints.md Defines a GET endpoint for paginated retrieval of multiple items. Requires imports for pagination utilities and response models. ```python from fastcrud import PaginatedListResponse, compute_offset, paginated_response from fastapi import Depends, HTTPException from sqlalchemy.ext.asyncio import AsyncSession from typing import Any from app.db.session import async_session from app.services.widget_service import WidgetService, get_widget_service from app.models.widget import WidgetRead from fastapi import APIRouter router = APIRouter() @router.get("/", response_model=PaginatedListResponse[WidgetRead]) async def list_widgets( db: Annotated[AsyncSession, Depends(async_session)], widget_service: Annotated[WidgetService, Depends(get_widget_service)], page: int = 1, items_per_page: int = 10, ) -> dict[str, Any]: result = await widget_service.get_paginated( skip=compute_offset(page, items_per_page), limit=items_per_page, db=db, ) return paginated_response(crud_data=result, page=page, items_per_page=items_per_page) ``` -------------------------------- ### Show Command Help Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/cli/commands.md Use the --help flag to display detailed information about any command or sub-command. ```bash uv run bp --help ``` ```bash uv run bp deploy --help ``` ```bash uv run bp deploy generate --help ``` ```bash uv run bp env --help ``` ```bash uv run bp env validate --help ``` -------------------------------- ### Get Current User API Endpoint (Bash) Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/index.md Retrieve the currently logged-in user's details by sending a GET request to the /api/v1/users/me endpoint. Use the saved session cookie for authentication. ```bash curl http://localhost:8000/api/v1/users/me -b cookies.txt ``` -------------------------------- ### Cache GET Endpoint with @cache Decorator Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/caching/index.md Use the @cache decorator to automatically cache GET endpoint responses. It invalidates the cache on POST/PUT/PATCH/DELETE requests to the same resource. Ensure the first parameter is `request: Request` for method inspection. The cache expires after the specified duration. ```python from typing import Annotated, Any from fastapi import APIRouter, Depends, Request from sqlalchemy.ext.asyncio import AsyncSession from ...infrastructure.cache import cache from ...infrastructure.database.session import async_session from .schemas import WidgetRead from .service import WidgetService router = APIRouter() @router.get("/{widget_id}", response_model=WidgetRead) @cache(key_prefix="widget", resource_id_name="widget_id", expiration=600) async def get_widget( request: Request, widget_id: int, db: Annotated[AsyncSession, Depends(async_session)], widget_service: Annotated[WidgetService, Depends(get_widget_service)], ) -> dict[str, Any]: return await widget_service.get_by_id(widget_id, db) ``` -------------------------------- ### Get Current User Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/first-run.md Retrieves the details of the currently authenticated user. ```APIDOC ## GET /api/v1/users/me ### Description Fetches the profile information for the user associated with the current session. ### Method GET ### Endpoint /api/v1/users/me ### Parameters #### Request Headers - **Cookie** - Required - Session cookie (e.g., `session_id=...`). ### Request Example ```bash curl http://localhost:8000/api/v1/users/me -b cookies.txt ``` ### Response #### Success Response (200) - **user** (object) - Details of the current user. ``` -------------------------------- ### Get Tier by Name Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/first-run.md Retrieves details for a specific service tier by its name. ```APIDOC ## GET /api/v1/tiers/{tier_name} ### Description Retrieves detailed information about a specific service tier. ### Method GET ### Endpoint /api/v1/tiers/{tier_name} ### Parameters #### Path Parameters - **tier_name** (string) - Required - The name of the tier to retrieve (e.g., `free`). ### Response #### Success Response (200) - **tier_details** (object) - Information about the specified tier. ``` -------------------------------- ### Get User by Username Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/api/index.md Retrieves a user's information by their unique username. ```APIDOC ## GET /{username} ### Description Retrieves a user's profile information using their username. ### Method GET ### Endpoint /{username} ### Parameters #### Path Parameters - **username** (str) - Required - The username of the user to retrieve. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **user** (UserRead) - The profile information of the requested user. #### Response Example ```json { "id": "123e4567-e89b-12d3-a456-426614174000", "username": "testuser", "email": "test@example.com" } ``` #### Error Response (404) - **detail** (str) - Message indicating the user was not found. #### Error Response Example (404) ```json { "detail": "User with username non_existent_user not found" } ``` ``` -------------------------------- ### Uninstall bp CLI Machine-Wide Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/cli/index.md Command to remove the machine-wide installation of the bp CLI. ```bash uv tool uninstall fastapi-boilerplate-cli ``` -------------------------------- ### Troubleshoot Redis Connection Error Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/installation.md Verify Redis server connectivity and start it if it's not running. ```bash redis-cli ping # should print PONG # If not, start it: redis-server ``` -------------------------------- ### Accessing Settings in the Application Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/configuration/settings-classes.md Demonstrates how to import and access the global `settings` object from anywhere in the application to retrieve configuration values. ```python from src.infrastructure.config.settings import get_settings settings = get_settings() print(settings.APP_NAME) ``` -------------------------------- ### Initialize v2 API Router Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/api/versioning.md Set up the main router for the v2 API, including importing and including v2-specific route modules. ```python # backend/src/interfaces/api/v2/__init__.py from fastapi import APIRouter # Import the v2-flavored route modules — see Step 2 below from ....modules.user.routes_v2 import router as users_router router = APIRouter(prefix="/v2") router.include_router(users_router, prefix="/users") # Re-export anything that didn't change in v2 from v1: # from ....modules.tier.routes import router as tiers_router # router.include_router(tiers_router, prefix="/tiers") ``` -------------------------------- ### Configure Initial Admin User Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/configuration/index.md Set the credentials for the initial administrator user. These are read by a script on the first run to set up the admin account. ```env ADMIN_NAME=Admin User ADMIN_EMAIL=admin@example.com ADMIN_USERNAME=admin ADMIN_PASSWORD=secure_password ``` -------------------------------- ### Get Single User Record by ID Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/database/crud.md Retrieve a single user record by its unique identifier. ```python user = await crud_users.get(db=db, id=user_id) ``` -------------------------------- ### Development Environment Configuration Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/configuration/environment-specific.md Use this `.env` file for local development. It includes settings for a local PostgreSQL database, relaxed security for plain HTTP, and verbose logging. ```env ENVIRONMENT=development DEBUG=true # App metadata APP_NAME=MyApp (Development) VERSION=0.1.0-dev # Database (local Postgres or Docker Compose) POSTGRES_USER=postgres POSTGRES_PASSWORD=postgres POSTGRES_DB=myapp_dev POSTGRES_SERVER=localhost # or "db" with Docker Compose POSTGRES_PORT=5432 # Security — keep a placeholder, never reuse for staging/prod SECRET_KEY=insecure-dev-key-replace-me # Sessions — relax cookie security for plain HTTP SESSION_SECURE_COOKIES=false CSRF_ENABLED=false # often easier when testing with curl # Cache / Rate limiter / Taskiq — point at localhost CACHE_REDIS_HOST=localhost RATE_LIMITER_REDIS_HOST=localhost TASKIQ_REDIS_HOST=localhost # Looser limits while iterating DEFAULT_RATE_LIMIT_LIMIT=1000 DEFAULT_RATE_LIMIT_PERIOD=60 # Admin user (used by setup_initial_data on first run) ADMIN_NAME=Dev Admin ADMIN_EMAIL=admin@localhost ADMIN_USERNAME=admin ADMIN_PASSWORD=admin123 # Logging LOG_DEVELOPMENT_VERBOSE=true # gives you DEBUG-level console output ``` -------------------------------- ### Get Tier by Name Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/api/endpoints.md Retrieves a specific tier by its name. If the tier is not found, a NotFoundException is raised. ```APIDOC ## GET /{name} ### Description Retrieves a tier by its name. ### Method GET ### Endpoint `/{name}` ### Parameters #### Path Parameters - **name** (str) - Required - The name of the tier to retrieve. ### Response #### Success Response (200) Details of the requested tier. #### Response Example { "example": "tier details" } ### Error Handling - **404 Not Found**: Returned if the tier with the specified name does not exist. ``` -------------------------------- ### Configure Application Settings Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/configuration/index.md Set the application name, version, environment, and debug mode. ```env APP_NAME=Your App Name VERSION=1.0.0 ENVIRONMENT=development # development | staging | production | local DEBUG=false ``` -------------------------------- ### Get a Specific Tier by Name Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/first-run.md Retrieve details for a specific service tier, identified by its name. ```bash curl http://localhost:8000/api/v1/tiers/free ``` -------------------------------- ### Environment Variables Configuration Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/installation.md Example environment variables for configuring the application, including database, cache, security, and initial admin user settings. Use 'localhost' for server/host values when not using Docker. ```env # Environment ENVIRONMENT=development # Database POSTGRES_USER=postgres POSTGRES_PASSWORD=postgres POSTGRES_DB=postgres POSTGRES_SERVER=db # use "localhost" without Docker POSTGRES_PORT=5432 # Cache (Redis) CACHE_BACKEND=redis CACHE_REDIS_HOST=redis # use "localhost" without Docker CACHE_REDIS_PORT=6379 # Security SECRET_KEY=insecure-change-this-in-production # Initial admin ADMIN_NAME=Admin User ADMIN_EMAIL=admin@example.com ADMIN_USERNAME=admin ADMIN_PASSWORD=your-secure-password ``` -------------------------------- ### Get a Single Item Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/api/endpoints.md Retrieves a single item by its ID. Handles not found errors and general exceptions. ```APIDOC ## GET /{widget_id} ### Description Retrieves a single item specified by its unique identifier. ### Method GET ### Endpoint /{widget_id} ### Parameters #### Path Parameters - **widget_id** (int) - Required - The unique identifier of the widget to retrieve. ### Response #### Success Response (200) - **widget** (WidgetRead) - The retrieved widget object. #### Error Response - **404** - If the widget with the specified ID is not found. - **500** - For unexpected server errors. ``` -------------------------------- ### Troubleshooting Container Startup Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/configuration/docker-setup.md If a container fails to start, check its logs using 'docker compose logs '. If the issue persists, try rebuilding the service image without cache. ```bash docker compose logs app ``` ```bash docker compose build --no-cache app ``` -------------------------------- ### Get Current User Profile Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/api/index.md Retrieves the profile of the currently authenticated user using session-based authentication. ```APIDOC ## GET /me ### Description Retrieves the profile of the currently authenticated user. ### Method GET ### Endpoint /me ### Parameters #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **user** (UserRead) - The profile information of the current user. #### Response Example ```json { "id": "123e4567-e89b-12d3-a456-426614174000", "username": "testuser", "email": "test@example.com" } ``` ``` -------------------------------- ### Add Custom Middleware Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/development.md Implement a custom middleware by subclassing `BaseHTTPMiddleware`. This example adds a timing header to responses. ```python import time from fastapi import Request, Response from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint from starlette.types import ASGIApp class TimingMiddleware(BaseHTTPMiddleware): async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response: start = time.perf_counter() response = await call_next(request) elapsed_ms = (time.perf_counter() - start) * 1000 response.headers["X-Process-Time-Ms"] = f"{elapsed_ms:.1f}" return response ``` -------------------------------- ### Create Admin User and Default Tier with Docker Compose Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/first-run.md Execute the initial data setup script using Docker Compose to create the admin user and default tier. ```bash docker compose exec web python -m scripts.setup_initial_data ``` -------------------------------- ### Get Current User's Widgets Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/api/endpoints.md Retrieves the widgets owned by the currently logged-in user. Requires authentication. ```APIDOC ## GET /me ### Description Retrieves the widgets owned by the currently logged-in user. ### Method GET ### Endpoint /me ### Parameters #### Query Parameters - **current_user** (dict[str, Any]) - Required - Dependency for getting the current user. - **db** (AsyncSession) - Required - Database session dependency. - **widget_service** (WidgetService) - Required - Widget service dependency. ### Response #### Success Response (200) - **list[WidgetRead]** - A list of widgets owned by the user. ``` -------------------------------- ### Run Database Migrations Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/getting-started/installation.md Apply database migrations using Alembic from the backend directory. ```bash cd backend uv run alembic upgrade head ``` -------------------------------- ### Run Migrations Job Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/configuration/docker-setup.md Use this service to run Alembic migrations before the application starts. It requires the `db` service to be available. ```yaml migrate: build: context: . dockerfile: Dockerfile target: migrate env_file: - .env depends_on: - db ``` -------------------------------- ### Declare Command Plugin Entry Point in pyproject.toml Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/cli/plugins.md Declare the entry point for your command plugin in the `pyproject.toml` file. This makes your Typer app discoverable by `bp` under the specified command name. ```toml [project] name = "bp-deploy-fly" version = "0.1.0" requires-python = ">=3.11" dependencies = ["typer>=0.12"] [project.entry-points."bp.commands"] fly = "bp_deploy_fly.cli:app" [tool.setuptools.packages.find] where = ["src"] ``` -------------------------------- ### Unit Test: Get User by ID (Not Found) Source: https://github.com/benavlabs/fastapi-boilerplate/blob/main/docs/user-guide/testing.md Tests the UserService.get_by_id method when the user is not found. Verifies that ResourceNotFoundError is raised. ```python # tests/unit/modules/user/test_service.py from unittest.mock import AsyncMock import pytest from src.modules.common.exceptions import ResourceNotFoundError from src.modules.user.service import UserService @pytest.mark.unit async def test_get_by_id_raises_when_missing(mocker): mock_crud = mocker.patch("src.modules.user.service.crud_users") mock_crud.get = AsyncMock(return_value=None) with pytest.raises(ResourceNotFoundError): await UserService().get_by_id(user_id=999, db=AsyncMock()) ```