evoai-backend-template

repository·main·Indexed 19 days ago

https://github.com/jiayuxu0/fastapi-template

An enterprise-grade FastAPI backend template (v1.0.0) featuring a production-ready three-layer architecture (API, Service, Repository, and Model layers). It includes built-in RBAC permission management, authentication, auditing, file management, and background task processing via arq and Redis. The template utilizes Tortoise ORM for data modeling, Aerich for database migrations, and provides a scaffolding CLI via create-fastapi-app.

Tokens
14.2K
Snippets
55
Records
75
Agent score
67%

What's inside evoai-backend-template

  1. Technical Stack Overview

    main

    The project is built using the following technologies:

    Backend Framework

    • FastAPI: High-performance web framework.
    • Tortoise ORM: Asynchronous ORM.
    • Pydantic: Data validation and settings management.
    • JWT: JSON Web Token authentication.

    Database

    • PostgreSQL: Recommended for production environments.
    • SQLite: Default for development environments.
    • Redis: Used for caching and session storage.
    • Aerich: Database migration tool.

    Development & DevOps

    • UV: Fast Python package manager.
    • Black / Ruff / MyPy: Code formatting, linting, and type checking.
    • Pytest: Testing framework (supports async testing).
    • Docker / Uvicorn / Nginx: Deployment and containerization.
  2. Understand the Three-Layer Architecture

    main

    The project follows a classic three-layer architecture to ensure maintainability, scalability, and testability. The flow of data and responsibilities is organized as follows:

    1. API Layer (src/api/v1/): Handles HTTP requests and responses. Responsibilities include route definition, request validation, response formatting, and unified error handling.
    2. Service Layer (src/services/): Implements core business logic. Responsibilities include enforcing business rules, permission verification, transaction management, and cache management.
    3. Repository Layer (src/repositories/): Manages data access and persistence. Responsibilities include CRUD operations, complex query building, data mapping (Model to DTO), and database transaction control.
    4. Model Layer (src/models/): Defines data structures using Tortoise ORM, including table relationships, indexes, and constraints.
    graph TB
        Client[客户端] --> Router[API路由层]
        Router --> Service[业务逻辑层]
        Service --> Repository[数据访问层]
        Repository --> Model[数据模型层]
        Model --> Database[(数据库)]
  3. Security Features: JWT and RBAC

    main

    The template includes enterprise-grade security features out of the box:

    • JWT Authentication: Uses a dual-token system with an Access Token (4-hour lifespan) and a Refresh Token (7-day lifespan).
    • RBAC (Role-Based Access Control): Provides fine-grained permission management by assigning roles to users.
    • Password Security: Uses the Argon2 hashing algorithm for secure password storage.
    • Rate Limiting: Includes protection against brute-force attacks via login frequency limits.
  4. Understand the 3-Layer Architecture

    main

    The template follows a clean 3-layer design to ensure separation of concerns:

    1. API Layer: Handles FastAPI routes, input validation, and response formatting.
    2. Service Layer: Contains business logic, permissions, validation, and cross-cutting concerns.
    3. Repository Layer: Manages data access, including CRUD operations and query building.
    4. Model Layer: Uses Tortoise ORM to define database models and relations.
  5. Understand the project directory structure

    main

    The project follows a layered architecture:

    • src/api/v1/: API routing layer (versioned)
    • src/services/: Business logic layer
    • src/repositories/: Data access layer
    • src/models/: Database models
    • src/schemas/: Data validation schemas (Pydantic)
    • src/core/: Core functionality and configuration
    • src/utils/: Utility functions
    • src/main.py: Application entry point
    • tests/: Test files
    • migrations/: Database migration files (managed by aerich)
    • pyproject.toml: Project configuration and dependencies
  6. How the three-layer architecture works

    main

    The project follows a strict separation of concerns to ensure maintainability and scalability. The data flows through these layers:

    1. API Layer (src/api/v1): Routes are kept "thin". They only handle parameter parsing, dependency injection, and response formatting.
    2. Service Layer (src/services): Contains all business logic, including permission checks, validation, and orchestration.
    3. Repository Layer (src/repositories): Handles all data access logic. This prevents ORM queries from leaking into the Service layer.
    4. Model Layer (src/models): Defines the data structures using Tortoise ORM. Tortoise models are kept separate from Pydantic schemas.

    Key Principle: All I/O (database, cache, task queue) is async-first.

  7. Add new API endpoints using the three-layer architecture

    main

    When adding new functionality, follow the project's architectural pattern by implementing these four layers:

    1. Model: Define data structures in src/models/.
    2. Repository: Implement data access logic in src/repositories/.
    3. Service: Implement business logic in src/services/.
    4. Router: Define API endpoints in src/api/v1/.
  8. Understand the standard API response formats

    main

    All API responses follow a unified JSON structure. Success responses include a code, a msg (usually "success"), and the payload in the data field. Error responses include a code, an error msg, and set data to null.

    ### Success Response
    ```json
    {
      "code": 200,
      "msg": "success",
      "data": {...}
    }

    Error Response

    {
      "code": 400,
      "msg": "error message",
      "data": null
    }
  9. Optimize Database and Performance

    main

    To ensure high performance in an enterprise-grade application, follow these patterns:

    Database Optimization

    • Use .select_related() to pre-load related data (one-to-one/many-to-one).
    • Use .prefetch_related() to optimize many-to-many or one-to-many queries.
    • Ensure appropriate database indexes are defined in your models.

    Caching Strategy

    • Use Redis to cache frequently accessed data.
    • Implement query result caching.
    • Set reasonable TTL (Time To Live) for cache expiration.

    Asynchronous Processing

    • Always use asynchronous I/O operations.
    • Utilize connection pooling.
    • Avoid blocking operations in the event loop.
  10. Quickstart: Install and run the FastAPI Template

    main

    Follow these steps to set up the project from scratch using the uv package manager.

    1. Prerequisites

    • Python: 3.11+
    • OS: Windows, macOS, or Linux
    • Memory: 4GB+ recommended
    • Storage: 1GB+ available

    2. Installation Steps

    Clone the repository

    git clone https://github.com/JiayuXu0/FastAPI-Template.git
    cd FastAPI-Template

    Install uv package manager

    • Linux/macOS: curl -LsSf https://astral.sh/uv/install.sh | sh
    • Windows: powershell -c "irm https://astral.sh/uv/install.ps1 | iex"
    • via pip: pip install uv

    Install dependencies

    # Install project dependencies
    uv sync
    
    # Install development dependencies
    uv sync --dev

    Configure environment

    Copy the example environment file and edit it with your settings:

    cp .env.example .env

    Initialize database

    uv run aerich init-db

    Start the service

    uv run uvicorn src:app --reload --host 0.0.0.0 --port 8000
    git clone https://github.com/JiayuXu0/FastAPI-Template.git
    cd FastAPI-Template
    # Install uv, sync dependencies, setup .env, init db, and run uvicorn
  11. Access API Documentation and Health Checks

    main

    Once the server is running at http://localhost:8000, you can access the following endpoints:

    • Interactive API Docs (Swagger UI): http://localhost:8000/docs
    • Alternative Docs (ReDoc): http://localhost:8000/redoc
    • Health Check Endpoint: http://localhost:8000/api/v1/base/health

    Default Credentials

    Use these to log in for the first time (change them immediately in production!):

    • Username: admin
    • Password: abcd1234
  12. Deploy with Docker

    main

    To deploy to production, build a Docker image and run the container. It is recommended to use environment variables for secrets in production instead of a .env file.

    # Build image
    docker build -t fastapi-template .
    
    # Run container
    docker run -d -p 8000:8000 --name fastapi-app fastapi-template
    # Production environment variables
    export SECRET_KEY="your-secret-key"
    export DB_HOST="your-db-host"
    export DB_PASSWORD="your-db-password"