### Install and Start Redis Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/development.md Instructions for installing and starting Redis on macOS, Ubuntu/Debian, or using Docker. Redis is required for Celery. ```bash # macOS brew install redis brew services start redis # Ubuntu/Debian sudo apt-get install redis-server sudo systemctl start redis # Windows # Download from https://github.com/microsoftarchive/redis/releases # Or use Docker: docker run -d -p 6379:6379 redis:alpine ``` -------------------------------- ### Start Application Services Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/deployment.md Commands to start the application using either Supervisor or Systemd. ```bash # Using Supervisor sudo supervisorctl reread sudo supervisorctl update sudo supervisorctl start fastapi-app # Using Systemd sudo systemctl daemon-reload sudo systemctl enable fastapi-app sudo systemctl start fastapi-app ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/eslam5464/fastapi-template/blob/master/README.md Install all project dependencies using 'uv'. Optionally install extra dependencies or pre-commit hooks. ```bash # Install dependencies uv sync --all-groups ``` ```bash # Install optional integrations as needed uv sync --all-groups --all-extras ``` ```bash # Install pre-commit hooks pre-commit install ``` -------------------------------- ### Signup Example Request (curl) Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/api.md An example using curl to send a POST request to the signup endpoint with form data. ```bash curl -X POST "http://localhost:8799/api/v1/auth/signup" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "username=johndoe&email=john@example.com&password=secretpassword&first_name=John&last_name=Doe" ``` -------------------------------- ### Set Up Environment Variables Source: https://github.com/eslam5464/fastapi-template/blob/master/README.md Copy the example environment file and edit it with your specific configuration. ```bash cp .env.example .env # Edit .env with your configuration ``` -------------------------------- ### Set Up Python Environment with uv Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/development.md Use uv to create and activate a virtual environment, and install project dependencies. Optional integrations can be installed using the --extra flag. ```bash # Install uv if you haven't already curl -LsSf https://astral.sh/uv/install.sh | sh # Create and activate virtual environment with dependencies uv sync # Optional integrations (install only what you use) uv sync --extra email --extra cloud-service --extra cache --extra task-queue --extra apple-services # Activate the environment source .venv/bin/activate # On Windows: .venv\Scripts\activate ``` -------------------------------- ### Install System Dependencies Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/deployment.md Update the system and install required packages including Python, PostgreSQL, Nginx, and uv. ```bash # Update system sudo apt update && sudo apt upgrade -y # Install dependencies sudo apt install -y python3.13 python3.13-venv python3-pip postgresql postgresql-contrib nginx supervisor # Install uv curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Install Test Dependencies Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/development.md Installs necessary dependencies for running tests using uv. ```bash uv sync --group test ``` -------------------------------- ### Environment Configuration Source: https://github.com/eslam5464/fastapi-template/blob/master/README.md Example configuration for environment variables and settings. ```env # Database POSTGRES_HOST=localhost POSTGRES_PORT=5432 POSTGRES_USER=postgres POSTGRES_PASSWORD=your-postgres-password POSTGRES_DB=postgres POSTGRES_DB_SCHEMA=fastapi_template # Security SECRET_KEY=your-secret-key ACCESS_TOKEN_EXPIRE_SECONDS=2582000 REFRESH_TOKEN_EXPIRE_SECONDS=2592000 # Server BACKEND_HOST=localhost BACKEND_PORT=8799 CURRENT_ENVIRONMENT=local # Redis (for caching and rate limiting) REDIS_HOST=localhost REDIS_PORT=6379 REDIS_PASS=your-redis-password # Rate Limiting RATE_LIMIT_ENABLED=true RATE_LIMIT_DEFAULT=100 RATE_LIMIT_WINDOW=60 # Celery & Background Tasks ENABLE_DATA_SEEDING=false SEEDING_USER_COUNT=100 # Email Providers resend_api_key=your_resend_api_key_here brevo_api_key=your_brevo_api_key_here ``` -------------------------------- ### Verify Installation and Run Application Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/development.md Run the main application script and verify it's working by accessing the API documentation endpoint. ```bash # Run the application python main.py # Check if it's working curl http://localhost:8799/docs ``` -------------------------------- ### Deploy Application Manually Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/deployment.md Steps to set up the application user, clone the repository, install dependencies, and run migrations. ```bash # Create application user sudo adduser --system --group --home /opt/fastapi-app fastapi # Clone repository sudo -u fastapi git clone /opt/fastapi-app cd /opt/fastapi-app # Setup Python environment sudo -u fastapi python3.13 -m venv .venv sudo -u fastapi .venv/bin/pip install uv sudo -u fastapi .venv/bin/uv sync # Set up environment variables sudo -u fastapi cp .env.example .env.prod sudo -u fastapi nano .env.prod # Configure production settings # Run database migrations sudo -u fastapi .venv/bin/alembic upgrade head ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/guides/getting-started.md Copy the example environment file and update it with your specific database, Redis, and secret configurations. ```bash copy .env.example .env ``` -------------------------------- ### Install Dependencies with Native TLS (Windows) Source: https://github.com/eslam5464/fastapi-template/blob/master/README.md If facing SSL issues on Windows, use 'uv' with the '--native-tls' flag to install dependencies. ```bash uv sync --all-groups --native-tls uv sync --native-tls --all-extras ``` -------------------------------- ### Login Example Request (curl) Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/api.md An example using curl to send a POST request to the login endpoint with form data. ```bash curl -X POST "http://localhost:8799/api/v1/auth/login" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "username=johndoe&password=secretpassword" ``` -------------------------------- ### Manual SSL Certificate Setup Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/deployment.md Commands to copy purchased SSL certificate and key files to the appropriate directories and set correct permissions for the private key. ```bash # Copy certificate files sudo cp yourdomain.crt /etc/ssl/certs/ sudo cp yourdomain.key /etc/ssl/private/ sudo chmod 600 /etc/ssl/private/yourdomain.key ``` -------------------------------- ### Set Up Python Environment with uv Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/guides/getting-started.md Create a virtual environment and install project dependencies using uv. Ensure you activate the virtual environment before running commands. ```bash python -m venv .venv .venv\Scripts\Activate.ps1 uv sync --all-groups ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/development.md Copy the example environment file and edit it with your specific configuration settings for database, security, server, and other services. ```bash cp .env.example .env ``` ```env # Database Configuration POSTGRES_HOST=localhost POSTGRES_PORT=5432 POSTGRES_USER=postgres POSTGRES_PASSWORD=your-postgres-password POSTGRES_DB=postgres POSTGRES_DB_SCHEMA=fastapi_template # Security Settings SECRET_KEY=your-super-secret-key-here ACCESS_TOKEN_EXPIRE_SECONDS=2582000 REFRESH_TOKEN_EXPIRE_SECONDS=2592000 # Server Configuration BACKEND_HOST=localhost BACKEND_PORT=8799 CURRENT_ENVIRONMENT=local # CORS Settings (for development) CORS_ORIGINS=localhost,0.0.0.0 # Logging LOG_LEVEL=DEBUG # Email Providers resend_api_key=your_resend_api_key_here brevo_api_key=your_brevo_api_key_here ``` -------------------------------- ### Integrate BackBlaze B2 Storage Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/development.md Example usage for initializing the client, managing buckets, and uploading files. ```python from app.services.back_blaze_b2 import BackBlaze, B2BucketTypeEnum from app.schemas import ApplicationData, UploadedFileInfo # Initialize BackBlaze client app_data = ApplicationData( app_id="your_application_key_id", app_key="your_application_key" ) b2_client = BackBlaze(app_data) # List available buckets buckets = b2_client.list_buckets() # Create a new bucket b2_client.create_bucket("my-new-bucket", B2BucketTypeEnum.ALL_PRIVATE) # Select a bucket for operations b2_client.select_bucket("my-bucket-name") # Upload a file file_version = b2_client.upload_file( local_file_path="/path/to/local/file.pdf", b2_file_name="documents/file.pdf", file_info=UploadedFileInfo(scanned=True) ) # Get download URL download_link = b2_client.get_download_url_by_name("documents/file.pdf") print(download_link.download_url) ``` -------------------------------- ### Build and Run Docker Containers Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/deployment.md Commands to build the image, start services, view logs, and scale the application. ```bash # Build the image docker build -t fastapi-app . # Run with Docker Compose docker-compose -f docker-compose.prod.yml up -d # View logs docker-compose -f docker-compose.prod.yml logs -f app # Scale the application docker-compose -f docker-compose.prod.yml up -d --scale app=3 ``` -------------------------------- ### Run Alembic Database Migrations Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/development.md Initialize Alembic if starting a new project and then apply all pending database migrations. ```bash # Initialize Alembic (only if starting fresh) alembic init alembic # Run existing migrations alembic upgrade head ``` -------------------------------- ### Cache Key Naming Convention Examples Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/backend-architecture.md Use a deterministic cache key structure for consistency. Examples include user IDs, IP addresses, and tokens. ```text cache:user:123 ``` ```text ratelimit:auth:192.168.1.1 ``` ```text blacklist:token:abc123 ``` -------------------------------- ### Install Optional Dependency Extras Source: https://github.com/eslam5464/fastapi-template/blob/master/README.md Use these commands to install optional provider groups for specific functionalities like email, cloud services, caching, task queues, or Apple services. ```bash uv sync --extra email ``` ```bash uv sync --extra cloud-service ``` ```bash uv sync --extra cache ``` ```bash uv sync --extra task-queue ``` ```bash uv sync --extra apple-services ``` -------------------------------- ### Run the FastAPI Application Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/guides/getting-started.md Start the FastAPI application by running the main Python file. ```bash python main.py ``` -------------------------------- ### Set Up Python Environment with pip and venv Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/development.md Create and activate a virtual environment using Python's built-in venv module, then install dependencies from requirements.txt. ```bash # Create virtual environment python -m venv .venv # Activate virtual environment source .venv/bin/activate # On Windows: .venv\Scripts\activate # Install dependencies pip install -r requirements.txt ``` -------------------------------- ### Resolve Import Errors Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/development.md Verify environment paths and dependency installation. ```bash # Check Python path echo $PYTHONPATH # Verify virtual environment which python pip list # Reinstall dependencies uv sync --reinstall ``` -------------------------------- ### API Signup Test Example Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/development.md An asynchronous test using httpx.AsyncClient to simulate a POST request to the signup endpoint and assert the response. ```python import pytest from httpx import AsyncClient from app.main import app @pytest.mark.asyncio async def test_create_user(): async with AsyncClient(app=app, base_url="http://test") as client: response = await client.post( "/api/v1/auth/signup", data={ "username": "testuser", "email": "test@example.com", "password": "testpass123", "first_name": "Test", "last_name": "User" } ) assert response.status_code == 201 assert "access_token" in response.json() ``` -------------------------------- ### Run Development Server Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/development.md Start the FastAPI application in development mode using the main script for auto-reloading or directly with uvicorn. ```bash # Using the main script (with auto-reload) python main.py # Or directly with uvicorn uvicorn app.main:app --reload --host 0.0.0.0 --port 8799 ``` -------------------------------- ### Initialize and Use Apple Pay Client Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/development.md Demonstrates basic client setup and common operations like transaction verification, subscription status checks, and history retrieval. ```python credentials = ApplePayStoreCredentials( private_key_id=settings.apple_pay_store_private_key_id, private_key=settings.apple_pay_store_private_key, issuer_id=settings.apple_pay_store_issuer_id, bundle_id=settings.apple_pay_store_bundle_id, root_certificate_path=settings.apple_pay_store_root_certificate_path ) apple_pay = ApplePay(credentials) # Verify a transaction transaction_id = "1000000123456789" try: transaction_info = apple_pay.get_transaction_info(transaction_id) print(f"Product ID: {transaction_info.product_id}") print(f"Purchase Date: {transaction_info.purchase_date}") print(f"Status: {transaction_info.status}") except ApplePayVerificationError as e: print(f"Verification failed: {e}") # Get subscription status original_transaction_id = "1000000123456789" subscription_status = apple_pay.get_subscription_status(original_transaction_id) for subscription in subscription_status.data: print(f"Subscription Group: {subscription.subscription_group_identifier}") print(f"Status: {subscription.status}") # Get transaction history history = apple_pay.get_transaction_history(original_transaction_id) for transaction in history.signed_transactions: print(f"Transaction: {transaction.transaction_id}") ``` -------------------------------- ### Perform BackBlaze B2 File and Bucket Operations Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/development.md Examples for managing temporary download links, deleting files, updating bucket settings, and removing buckets. ```python from pydantic import AnyUrl temp_link = b2_client.get_temporary_download_link( url=AnyUrl(download_link.download_url), valid_duration_in_seconds=3600 # 1 hour ) # Delete a file b2_client.delete_file( file_id=file_version.id_, file_name="documents/file.pdf" ) # Update bucket settings b2_client.update_selected_bucket( bucket_type=B2BucketTypeEnum.ALL_PUBLIC ) # Delete bucket b2_client.delete_selected_bucket() ``` -------------------------------- ### Manage Celery Beat Source: https://github.com/eslam5464/fastapi-template/blob/master/README.md Commands to start the Celery beat scheduler. ```bash # Linux/macOS ./scripts/celery_beat.sh # Windows .\scripts\celery_beat.bat # Or directly celery -A app.services.task_queue beat --loglevel=info ``` -------------------------------- ### Manage Pre-commit Hooks Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/development.md Install, run, and update pre-commit hooks to maintain code quality automatically before each commit. ```bash # Install pre-commit hooks pre-commit install # Run hooks manually pre-commit run --all-files # Update hooks pre-commit autoupdate ``` -------------------------------- ### Pytest Fixture Examples Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/backend-architecture.md Demonstrates how to define mock fixtures for dependencies and factory fixtures for generating data. Use mock_ for fakes and _factory for data generation. ```python from collections.abc import Callable from unittest.mock import AsyncMock import pytest @pytest.fixture def mock_user_repo() -> AsyncMock: return AsyncMock() @pytest.fixture def user_factory() -> Callable[..., dict[str, str]]: def _create(**overrides: str) -> dict[str, str]: base = {"email": "test@example.com", "name": "Test User"} return {**base, **overrides} return _create ``` -------------------------------- ### BackBlaze B2 CLI for Backups Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/deployment.md Commands for interacting with BackBlaze B2 storage using the B2 CLI. Includes installation, authorization, uploading, listing, and downloading backup files. ```bash # Install B2 CLI pip install b2 # Authorize account b2 authorize-account $B2_APPLICATION_KEY_ID $B2_APPLICATION_KEY # Upload backup to B2 b2 upload-file your-backup-bucket /path/to/backup.sql.gz backups/backup_$DATE.sql.gz # List backups b2 ls your-backup-bucket backups/ # Download backup b2 download-file-by-name your-backup-bucket backups/backup_$DATE.sql.gz /path/to/restore/ ``` -------------------------------- ### Initialize and Use Firestore Service Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/development.md Demonstrates initializing the Firestore service with credentials and performing basic CRUD operations: adding, getting, updating, fetching all, and removing documents. Ensure `FirebaseServiceAccount` schema is correctly defined and populated. ```python from app.services.firestore import Firestore from app.schemas.firebase import FirebaseServiceAccount # Initialize Firestore (uses singleton pattern) service_account = FirebaseServiceAccount( type="service_account", project_id="your-project-id", # ... other credentials ) firestore_service = Firestore(service_account) # Add a document firestore_service.add_document( collection_name="users", document_id="user123", data={ "name": "John Doe", "email": "john@example.com", "preferences": { "theme": "dark", "notifications": True } } ) # Get a document user_data = firestore_service.get_document( collection_name="users", document_id="user123" ) if user_data: print(f"User: {user_data['name']}") # Update a document firestore_service.update_document( collection_name="users", document_id="user123", data={ "preferences.theme": "light", # Nested field update "last_login": "2025-01-19T10:30:00Z" } ) # Fetch all documents from collection all_users = firestore_service.fetch_all_documents("users") for user in all_users: print(f"User: {user['name']}") # Remove a document firestore_service.remove_document( collection_name="users", document_id="user123" ) ``` -------------------------------- ### Initialize and Use GCS Client Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/development.md This Python code demonstrates how to initialize the GoogleCloudStorage client, select a bucket, and perform common file operations like upload, download, and deletion. It also shows how to get public and signed URLs. ```python from app.services.gcs import GoogleCloudStorage # Initialize GCS client gcs_client = GoogleCloudStorage( project_id="your-project-id", credentials_json=settings.gcs_credentials_json ) # Select a bucket gcs_client.select_bucket("my-bucket-name") # Upload a file blob = gcs_client.upload_file( local_file_path="/path/to/local/file.pdf", destination_blob_name="documents/file.pdf", content_type="application/pdf" ) # Download a file gcs_client.download_file( source_blob_name="documents/file.pdf", destination_file_path="/path/to/download/file.pdf" ) # Get public URL (for public buckets) public_url = gcs_client.get_public_url("documents/file.pdf") # Generate signed URL (for private buckets) signed_url = gcs_client.generate_signed_url( blob_name="documents/file.pdf", expiration_minutes=60 ) # Delete a file gcs_client.delete_file("documents/file.pdf") # List files in bucket files = gcs_client.list_files(prefix="documents/") for file in files: print(f"File: {file.name}, Size: {file.size}") ``` -------------------------------- ### Domain-Specific Repository Example Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/backend-architecture.md Extends a generic base repository to add custom query methods for specific domain models. Requires an AsyncSession for database operations. ```python class ResourceRepository(BaseRepository[ResourceModel, CreateResourceSchema, UpdateResourceSchema]): """Domain-specific repository with custom query methods.""" def __init__(self, session: AsyncSession): super().__init__(session, ResourceModel) async def get_by_category( self, category: str, skip: int = 0, limit: int = 100, ) -> list[ResourceModel]: """Get resources filtered by category.""" stmt = ( select(self.model) .where(self.model.category == category) .offset(skip) .limit(limit) .order_by(self.model.created_at.desc()) ) result = await self.session.execute(stmt) return list(result.scalars().all()) async def get_by_time_range( self, start_time: int, end_time: int, ) -> list[ResourceModel]: """Get resources within an inclusive time window.""" stmt = ( select(self.model) .where(self.model.timestamp.between(start_time, end_time)) .order_by(self.model.timestamp.asc()) ) result = await self.session.execute(stmt) return list(result.scalars().all()) ``` -------------------------------- ### Create Custom Rate Limiters Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/development.md Create custom rate limiters using `create_rate_limit` for specific endpoints with custom limits and windows. This example demonstrates creating limits for heavy operations and user-based uploads. ```python from app.api.v1.deps.rate_limit import create_rate_limit # Custom limit for heavy operations (5 requests per 5 minutes) heavy_limit = create_rate_limit(limit=5, window=300, prefix="heavy") @router.post("/export", dependencies=[Depends(heavy_limit)]) async def export_large_file(): pass # Custom user-based limit (20 uploads per minute per user) upload_limit = create_rate_limit( limit=20, window=60, prefix="upload", use_user_id=True ) @router.post("/upload", dependencies=[Depends(upload_limit)]) async def upload_file(current_user: User = Depends(get_current_user)): pass ``` -------------------------------- ### Get Current User Endpoint Request Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/api.md Example cURL command to retrieve information about the currently authenticated user. Requires an Authorization header with a Bearer token. ```bash curl -X GET "http://localhost:8799/api/v1/users/me" \ -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..." ``` -------------------------------- ### Initialize AuthService Source: https://context7.com/eslam5464/fastapi-template/llms.txt Demonstrates how to initialize the AuthService with a repository. ```python from app.services.auth_service import AuthService from app.repos.user import UserRepo from app.schemas import UserCreate # Initialize service with repository auth_service = AuthService(user_repo=UserRepo(db_session)) ``` -------------------------------- ### Configure and Migrate Database Source: https://github.com/eslam5464/fastapi-template/blob/master/README.md Create the PostgreSQL database and run Alembic migrations to set up the schema. ```bash # Create database createdb fastapi_template # Run migrations alembic upgrade head ``` -------------------------------- ### Install Certbot and Obtain SSL Certificate Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/deployment.md Installs Certbot with the Nginx plugin and obtains an SSL certificate for the specified domains. It also includes commands to test auto-renewal and set up a cron job for automatic certificate renewal. ```bash # Install Certbot sudo apt install certbot python3-certbot-nginx # Obtain certificate sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com # Test auto-renewal sudo certbot renew --dry-run # Set up auto-renewal cron job echo "0 12 * * * /usr/bin/certbot renew --quiet" | sudo crontab - ``` -------------------------------- ### Firestore Security Rules Example Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/deployment.md Example Firestore security rules demonstrating access control for user preferences and server-only writes to analytics collections. Ensure these rules align with your application's specific security requirements. ```javascript rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { // Example: Authenticated users can read/write their own data match /user_preferences/{userId} { allow read, write: if request.auth != null && request.auth.uid == userId; } // Example: Only server can write to certain collections match /analytics/{document=**} { allow read: if request.auth != null; allow write: if false; // Server-side only } } } ``` -------------------------------- ### Initialize BackBlaze B2 Client Source: https://context7.com/eslam5464/fastapi-template/llms.txt Set up the BackBlaze B2 client using application credentials. Requires `ApplicationData` containing `app_id` and `app_key`. ```python from app.services.back_blaze_b2 import BackBlaze, B2BucketTypeEnum from app.schemas import ApplicationData, UploadedFileInfo # Initialize client app_data = ApplicationData( app_id="your_key_id", app_key="your_application_key" ) b2_client = BackBlaze(app_data) ``` -------------------------------- ### GET /api/v1/users/me Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/api.md Retrieves information for the currently authenticated user. ```APIDOC ## GET /api/v1/users/me ### Description Get current authenticated user information. ### Method GET ### Endpoint /api/v1/users/me ### Response #### Success Response (200) - **id** (integer) - User ID - **username** (string) - Username - **email** (string) - Email address - **first_name** (string) - First name - **last_name** (string) - Last name - **created_at** (string) - Creation timestamp - **updated_at** (string) - Update timestamp #### Response Example { "id": 1, "username": "johndoe", "email": "john@example.com", "first_name": "John", "last_name": "Doe", "created_at": "2025-01-19T10:30:00Z", "updated_at": "2025-01-19T10:30:00Z" } ``` -------------------------------- ### GET /health Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/api.md Checks the health status of the API and its dependencies. ```APIDOC ## GET /health ### Description Check the health status of the API and its dependencies. ### Method GET ### Endpoint /health ### Response #### Success Response (200) - **status** (string) - healthy - **timestamp** (string) - Current timestamp - **version** (string) - API version #### Response Example { "status": "healthy", "timestamp": "2025-01-19T10:30:00Z", "version": "0.1.0" } ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/eslam5464/fastapi-template/blob/master/README.md Clone the project repository and change into the project directory. ```bash git clone cd FastApi-Template ``` -------------------------------- ### Get Current User API Source: https://context7.com/eslam5464/fastapi-template/llms.txt Retrieves the authenticated user's profile information. ```APIDOC ## GET /v1/users/me ### Description Returns the authenticated user's profile information. Requires a valid access token and is rate-limited. ### Method GET ### Endpoint /v1/users/me ### Parameters #### Headers - **Authorization** (string) - Required - Bearer token for authentication. ### Request Example ```bash curl -X GET http://localhost:8799/v1/users/me \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` ### Response #### Success Response (200 OK) - **id** (integer) - The user's unique identifier. - **username** (string) - The user's username. - **email** (string) - The user's email address. - **first_name** (string) - The user's first name. - **last_name** (string) - The user's last name. - **created_at** (string) - Timestamp when the user was created (ISO 8601 format). - **updated_at** (string) - Timestamp when the user was last updated (ISO 8601 format). #### Response Example ```json { "id": 1, "username": "john_doe1", "email": "john@example.com", "first_name": "John", "last_name": "Doe", "created_at": "2024-01-15T10:30:00Z", "updated_at": "2024-01-15T10:30:00Z" } ``` #### Rate Limit Headers - **X-RateLimit-Limit** (integer) - The maximum number of requests allowed in the current window. - **X-RateLimit-Remaining** (integer) - The number of requests remaining in the current window. - **X-RateLimit-Reset** (integer) - The timestamp (in milliseconds) when the rate limit window resets. ``` -------------------------------- ### Initialize Database Engine Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/backend-architecture.md Sets up the SQLAlchemy asynchronous engine using the configuration settings. ```python from yarl import URL from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine from app.core.config import settings # Create async engine engine = create_async_engine( settings.db_url.human_repr(), # yarl URL → string echo=settings.debug, pool_pre_ping=True, ) ``` -------------------------------- ### Manage Celery Worker Source: https://github.com/eslam5464/fastapi-template/blob/master/README.md Commands to start the Celery worker process across different operating systems. ```bash # Linux/macOS ./scripts/celery_worker.sh # Windows .\scripts\celery_worker.bat # Or directly celery -A app.services.task_queue worker --loglevel=info --pool=solo ``` -------------------------------- ### Frontend CSRF Token Integration Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/development.md Example of including the CSRF token in the request header for state-changing operations. ```javascript // Include CSRF token in requests const csrfToken = document.querySelector('meta[name="csrf-token"]').content; fetch('/api/v1/users/me', { method: 'PUT', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': csrfToken }, body: JSON.stringify(userData) }); ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/eslam5464/fastapi-template/blob/master/README.md Create a Python virtual environment and activate it for managing project dependencies. ```bash python -m venv .venv ``` ```bash # On Linux / macOS source .venv/bin/activate # On Windows (PowerShell) .venv\Scripts\Activate.ps1 ``` -------------------------------- ### API Testing with Python Requests Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/api.md Example of authenticating and accessing a protected user endpoint using the requests library. ```python import requests # Base URL base_url = "http://localhost:8799/api/v1" # Login response = requests.post( f"{base_url}/auth/login", data={ "username": "testuser", "password": "testpass" } ) tokens = response.json() # Use access token headers = {"Authorization": f"Bearer {tokens['access_token']}"} user_response = requests.get(f"{base_url}/users/me", headers=headers) user_data = user_response.json() ``` -------------------------------- ### Create Test Database Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/development.md Creates a PostgreSQL database specifically for testing. ```bash createdb fastapi_template_test ``` -------------------------------- ### Enable Nginx Site and Reload Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/deployment.md Commands to enable the Nginx configuration file, test its syntax, and reload the Nginx service to apply changes. ```bash sudo ln -s /etc/nginx/sites-available/fastapi-app /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl reload nginx ``` -------------------------------- ### API Testing with JavaScript Fetch Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/api.md Example of authenticating and accessing a protected user endpoint using the native fetch API. ```javascript // Login const loginResponse = await fetch("/api/v1/auth/login", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", }, body: new URLSearchParams({ username: "testuser", password: "testpass", }), }); const tokens = await loginResponse.json(); // Use access token const userResponse = await fetch("/api/v1/users/me", { headers: { Authorization: `Bearer ${tokens.access_token}`, }, }); const userData = await userResponse.json(); ``` -------------------------------- ### Example Error Response Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/api/reference.md Errors in this API follow the standard FastAPI/HTTP exception response format, including a 'detail' field. ```json { "detail": "Unauthorized" } ``` -------------------------------- ### Initialize and Use GCS Client Source: https://context7.com/eslam5464/fastapi-template/llms.txt Set up and interact with Google Cloud Storage for file operations. Requires a `ServiceAccount` object for authentication. ```python from app.services.gcs import GCS from app.schemas import ServiceAccount from io import BytesIO # Initialize with service account service_account = ServiceAccount( project_id="my-project", private_key_id="key-id", private_key="-----BEGIN PRIVATE KEY-----\n...", client_email="service@project.iam.gserviceaccount.com", client_id="123456789" ) async with GCS(service_account) as gcs: # List all buckets buckets = await gcs.get_all_buckets(project="my-project") ``` -------------------------------- ### Configure PostgreSQL Database Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/deployment.md Create the application database and user within the PostgreSQL shell. ```sql # Switch to postgres user sudo -u postgres psql # Create database and user CREATE DATABASE fastapi_app; CREATE USER fastapi_user WITH ENCRYPTED PASSWORD 'secure_password'; GRANT ALL PRIVILEGES ON DATABASE fastapi_app TO fastapi_user; ALTER USER fastapi_user CREATEDB; \q ``` -------------------------------- ### Get and Delete BackBlaze B2 Files Source: https://context7.com/eslam5464/fastapi-template/llms.txt Retrieve details about a specific file using its ID and delete files from BackBlaze B2. ```python # Get file details file_info = await b2_client.get_file_details(file_version.id_) # Delete file await b2_client.delete_file( file_id=file_version.id_, file_name="documents/file.pdf" ) ``` -------------------------------- ### Implement Repository Pattern Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/architecture.md Abstracts database access logic, specifically demonstrating a query by email using an asynchronous session. ```python # Repository pattern example class UserRepository(BaseRepository[User]): async def get_by_email( self, session: AsyncSession, email: str ) -> Optional[User]: result = await session.execute( select(User).where(User.email == email) ) return result.scalar_one_or_none() ``` -------------------------------- ### Get BackBlaze B2 Download URLs Source: https://context7.com/eslam5464/fastapi-template/llms.txt Retrieve direct download URLs for files, including temporary links with authentication tokens. ```python # Get download URL by file name download_link = await b2_client.get_download_url_by_name("documents/file.pdf") print(f"Download URL: {download_link.download_url}") # Get temporary download link with auth token from pydantic import AnyUrl temp_link = await b2_client.get_temporary_download_link( url=AnyUrl(f"https://...?fileId={file_version.id_}"), valid_duration_in_seconds=3600 # 1 hour ) print(f"Temp URL: {temp_link.download_url}?Authorization={temp_link.auth_token}") ``` -------------------------------- ### User Authentication and Token Management Source: https://context7.com/eslam5464/fastapi-template/llms.txt Demonstrates registering a new user, authenticating an existing user, validating access tokens, refreshing tokens, and generating random passwords using the AuthService. ```python signup_data = UserCreate( username="john_doe1", email="john@example.com", first_name="John", last_name="Doe", hashed_password=auth_service.get_password_hash("SecurePass123!") ) tokens = await auth_service.register_user(signup_data) print(f"Access Token: {tokens['access_token']}") print(f"Refresh Token: {tokens['refresh_token']}") # Authenticate existing user tokens = await auth_service.authenticate_user( username="john_doe1", password="SecurePass123!" ) # Validate access token and get user user = await auth_service.validate_access_token(tokens['access_token']) print(f"Authenticated user: {user.username}") # Refresh tokens new_tokens = await auth_service.refresh_tokens(tokens['refresh_token']) # Generate random secure password random_password = AuthService.generate_random_password(length=16) ``` -------------------------------- ### Troubleshoot Database Connections Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/development.md Verify PostgreSQL status and environment configuration. ```bash # Check PostgreSQL is running pg_ctl status # Check database exists psql -l | grep fastapi_template # Verify database env vars echo $POSTGRES_HOST echo $POSTGRES_DB ``` -------------------------------- ### Marked End-to-End Test Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/backend-architecture.md An example of an end-to-end test marked with `@pytest.mark.e2e`. This test is intended to exercise complete user flows against a running environment. ```python import pytest @pytest.mark.e2e def test_user_signup_journey() -> None: # Exercise complete user flow against a running environment. assert True ``` -------------------------------- ### Logout Endpoint Request Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/api.md Example cURL command to log out by revoking the current access token. Requires an Authorization header with a Bearer token. ```bash curl -X POST "http://localhost:8799/api/v1/auth/logout" \ -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..." ``` -------------------------------- ### Health Check Endpoint Request Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/api.md Example cURL command to check the health status of the API. This endpoint returns the API's status and a timestamp. ```bash curl -X GET "http://localhost:8799/health" ``` -------------------------------- ### Create PostgreSQL Database Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/development.md Create the PostgreSQL database using either the command line or SQL commands. ```bash # Using PostgreSQL command line createdb fastapi_template # Or using SQL psql -c "CREATE DATABASE fastapi_template;" ``` -------------------------------- ### Initialize Core Configuration File Source: https://github.com/eslam5464/fastapi-template/blob/master/docs/backend-architecture.md Placeholder for the application configuration management module located in the core layer. ```python # ============================================================================= # app/core/config.py - Configuration Management ```