Menu

Overview

Relevant source files

FastAPI Best Architecture (FBA) is an enterprise-level backend solution that implements a pseudo 3-tier architecture pattern for FastAPI applications. This page introduces the project's core concepts, architectural design, and major system components.

For setup instructions, see Getting Started. For detailed architectural explanations, see Architecture & Core Concepts.


What is FastAPI Best Architecture

FastAPI Best Architecture is a production-ready backend framework designed for enterprise applications. It combines FastAPI's modern async capabilities with a layered architecture pattern that separates concerns across five distinct layers: api, schema, service, crud, and model.

Core Design Principles:

  • Layered Architecture: Clear separation between presentation, business logic, and data access
  • Async-First: All database and I/O operations use Python's async/await syntax
  • Dependency Injection: FastAPI's DI system manages authentication, database sessions, and permissions
  • Type Safety: Pydantic v2 for runtime validation, SQLAlchemy 2.0 for type-safe ORM queries
  • Extensibility: Plugin system allows feature additions without modifying core code
  • Security: Multi-layer authentication and authorization with JWT, RBAC, and row-level permissions

Key Capabilities:

FeatureImplementation
AuthenticationJWT tokens with Redis whitelist via DepsJwtAuth
AuthorizationCasbin RBAC with rbac_verify() and data scope filtering
Task ProcessingCelery with database-driven scheduling and distributed locks
Plugin SystemHot-loadable modules via PluginManager.load_plugins()
Code GenerationAuto-generate CRUD operations from database schema
LoggingRequest tracing with ctx.request_id, async audit logs
CLI Managementfba commands for service control and plugin installation

The project targets enterprise developers who need a scalable, maintainable backend architecture with built-in security, observability, and operational tooling.

Sources: README.md1-43 README.zh-CN.md1-40


Pseudo 3-Tier Architecture

FBA implements a pseudo 3-tier architecture that separates concerns into five layers: api, schema, service, crud, and model. This design is inspired by Java enterprise patterns (controller → service → DAO) but adapted for Python's async/await capabilities.

Layer Mapping

WorkflowJava EquivalentFBA DirectoryResponsibility
ViewControllerapi/Route definitions, HTTP handling
Data TransferDTOschema/Request/response validation
Business LogicService + Implservice/Business rules, orchestration
Data AccessDAO / Mappercrud/Database query operations
ModelModel / Entitymodel/SQLAlchemy ORM entities

Example Structure for User Module:

backend/app/admin/
├── api/v1/user.py          # @router.get("/admin/v1/users/{pk}")
├── schema/user.py          # CreateUserParam, GetUserInfoDetails
├── service/user_service.py # UserService.get_userinfo(), .update()
├── crud/crud_user.py       # CRUDUser.get(), .get_by_username()
└── model/sys_user.py       # User(MappedAsDataclass, Base)

Request Flow Diagram

Diagram: Data Flow Through 5-Layer Architecture

Architectural Rules:

  1. Unidirectional Flow: Requests flow downward (API → Schema → Service → CRUD → Model), responses flow upward
  2. No Layer Skipping: API layer cannot directly call CRUD or Model layers
  3. Dependency Injection: DepsJwtAuth, DepsRBAC, and get_db() are injected at API layer
  4. Schema Validation: All API inputs/outputs pass through Pydantic schema classes
  5. Business Logic Isolation: Service layer handles all business rules, including filter_data_permission()

Code Example:

Sources: README.md26-43 backend/app/admin/api/v1/user.py backend/app/admin/schema/user.py backend/app/admin/service/user_service.py backend/app/admin/crud/crud_user.py backend/app/admin/model/sys_user.py


System Architecture

FBA consists of seven major subsystems organized in a layered architecture. The diagram below shows how these components interact during request processing.

Diagram: Overall System Architecture

Major Components:

LayerComponentsKey Files
Application CoreFastAPI app with pseudo 3-tier architecturebackend/main.py, backend/core/registrar.py
PresentationAPI routes, middleware stackbackend/app/admin/api/, backend/middleware/
Business LogicService classes, schemasbackend/app/admin/service/, backend/app/admin/schema/
Data AccessCRUD operations, ORM modelsbackend/app/admin/crud/, backend/app/admin/model/
Plugin SystemHot-loadable feature modulesbackend/plugin/manager.py, backend/plugin/*/
Task SystemCelery distributed tasksbackend/app/task/celery.py, backend/app/task/scheduler.py
StoragePostgreSQL, Redis, RabbitMQbackend/database/db_postgres.py, backend/database/db_redis.py

Data Flow:

  1. HTTP requests enter through middleware pipeline (JWT auth → RBAC → logging)
  2. Routed to API endpoints in backend/app/admin/api/v1/
  3. Validated by Pydantic schemas in backend/app/admin/schema/
  4. Processed by service layer with business logic
  5. Data operations executed via CRUD layer
  6. ORM models interact with PostgreSQL database
  7. Responses flow back through the same layers

Plugin Integration:

  • PluginManager.load_plugins() scans backend/plugin/ for plugin.toml files
  • Plugins inject routes into existing apps (extend-level) or create new routes (app-level)
  • Plugin status tracked in Redis, can be enabled/disabled at runtime

Async Tasks:

  • DatabaseScheduler reads sys_task table for dynamic Celery Beat schedules
  • Workers process tasks using gevent pool (1000 concurrency)
  • Flower provides monitoring at http://localhost:8555

Sources: backend/main.py backend/core/registrar.py backend/plugin/manager.py backend/app/task/celery.py backend/app/task/scheduler.py backend/database/db_postgres.py backend/database/db_redis.py


Key Features Summary

FBA provides five major feature categories that distinguish it as an enterprise backend solution:

1. Authentication & Authorization

Multi-layer security system:

  • JWT authentication with access/refresh tokens stored in Redis whitelist
  • Casbin RBAC for endpoint-level permissions via rbac_verify()
  • Data scope filtering for row-level security (5 scope types: all, custom, dept, dept+children, self)
  • OAuth2 social login (GitHub, Google, LinuxDo) via plugin system
  • Password policies with history tracking, expiry, and complexity rules

Key Components: DepsJwtAuth, DepsRBAC, filter_data_permission(), backend/common/security/

See: Authentication & Authorization

2. Plugin System

Hot-loadable architecture for feature extension:

  • Install plugins from ZIP files or Git repositories without code changes
  • Two plugin types: extend-level (inject into existing routes) and app-level (new routes)
  • Automatic dependency installation and SQL script execution
  • Runtime enable/disable via admin API
  • Built-in plugins: Dict, OAuth2, Config, Email, Code Generator

Key Components: PluginManager, backend/plugin/manager.py, plugin.toml configuration

See: Plugin System

3. Database-Driven Task Scheduling

Dynamic Celery task management:

  • DatabaseScheduler replaces file-based beat schedule with database storage
  • CRUD APIs for task creation, modification, and control at runtime
  • Distributed locks prevent duplicate task execution in multi-instance deployments
  • Timezone-aware crontab expressions via TzAwareCrontab
  • Flower monitoring at port 8555

Key Components: DatabaseScheduler, sys_task table, backend/app/task/scheduler.py

See: Background Processing

4. Request Tracing & Logging

Multi-level observability system:

  • Request ID (ctx.request_id) generated per request for correlation
  • Access logs track request duration and status codes
  • Opera logs capture user actions with async queue processing
  • Login logs audit authentication attempts
  • Automatic desensitization of sensitive data (passwords, tokens)

Key Components: ContextMiddleware, OperaLogQueue, backend/middleware/opera_log_middleware.py

See: Request Processing

5. Code Generation

Auto-generate CRUD scaffolding from database schema:

  • Import table structure with column types and constraints
  • Generate model, schema, CRUD, service, and API layers
  • Template-based code generation with customization support
  • CLI commands: fba codegen import, fba codegen
  • Web UI at /code_gen/v1/preview for preview before generation

Key Components: GenService, backend/plugin/code_gen/, template engine

See: CLI Tool & Commands

Sources: backend/common/security/jwt.py backend/common/security/rbac.py backend/plugin/manager.py backend/app/task/scheduler.py backend/middleware/opera_log_middleware.py backend/plugin/code_gen/service/gen_service.py


Technology Stack

Core Dependencies

ComponentLibraryVersionPurpose
Web FrameworkFastAPILatestAsync API endpoints
ASGI ServerGranianLatestProduction ASGI server
ORMSQLAlchemy2.0+Async database toolkit
ValidationPydanticv2Data validation
Task QueueCeleryLatestAsync task processing
DatabasePostgreSQL16+Primary data store
CacheRedisLatestSessions, tokens, locks
Message BrokerRabbitMQLatestCelery message queue
RBACCasbinLatestPermission policies
LoggingLoguruLatestStructured logs
Package ManageruvLatestFast dependency management
Code QualityRuffLatestLinting and formatting

Database Schema

FBA uses PostgreSQL 16+ as the primary database with custom SQLAlchemy types:

  • TimeZone: Timezone-aware datetime mapping (TIMESTAMP WITH TIME ZONE)
  • UniversalText: Cross-database text type (TEXT for PostgreSQL, LONGTEXT for MySQL)

Primary Key Strategies:

  • id_key(): Auto-increment integers for single-instance deployments
  • snowflake_id_key(): Distributed snowflake IDs for horizontal scaling

Core Tables:

  • sys_user: User accounts and profiles
  • sys_role: Role definitions and hierarchies
  • sys_menu: Menu items and permissions
  • sys_dept: Department/organization structure
  • sys_data_scope: Data permission scopes
  • sys_data_rule: Row-level permission rules
  • sys_opera_log: Operation audit logs
  • sys_login_log: Authentication audit trail
  • sys_task: Celery task schedules

See: Database Layer for detailed schema documentation

Built-in Plugins

Five plugins are included by default in backend/plugin/:

PluginTypeRoute PrefixPurpose
dictApp/dict/v1Data dictionary (types and values)
oauth2Extend/admin/v1/authSocial login (GitHub, Google, LinuxDo)
configApp/config/v1System configuration key-value store
emailApp/email/v1Email sending and verification codes
code_genApp/code_gen/v1CRUD code generation from schema

Plugin Types:

  • Extend: Injects routes into existing routers (e.g., OAuth2 extends admin auth routes)
  • App: Creates new top-level routes (e.g., /dict/v1/type, /config/v1/list)

Plugin Management:

See: Plugin System for architecture details

Sources: backend/plugin/manager.py backend/plugin/dict/plugin.toml backend/plugin/oauth2/plugin.toml backend/plugin/code_gen/service/gen_service.py backend/database/db_postgres.py


Request Processing Flow

Requests flow through multiple layers from client to database. The diagram below shows the complete processing pipeline.

Diagram: Request Processing Pipeline

Processing Stages:

StageMiddlewareDurationActions
1. Contextcontext_middleware.py<1msGenerate ctx.request_id, parse ctx.trace_id
2. Timingaccess_middleware.py<1msRecord ctx.start_time
3. I18ni18n_middleware.py<1msParse Accept-Language to ctx.language
4. Authjwt_middleware.py2-5msDecode JWT, check Redis whitelist
5. RBACrbac_verify() dependency2-5msVerify Casbin policy
6. Statestate_middleware.py2-5msParse IP location, user agent
7. RoutingFastAPI router<1msMatch endpoint
8. BusinessService layer10-50msExecute business logic
9. DatabaseCRUD layer10-100msSQLAlchemy queries
10. Loggingopera_log_middleware.py<1msQueue operation log

Key Processing Components:

  • Middleware Pipeline: 6 middleware layers execute in order before routing
  • Context Variables: ctx.request_id, ctx.trace_id, ctx.user, ctx.ip, ctx.language available throughout request
  • JWT Validation: Tokens checked against Redis TOKEN_REDIS_PREFIX:{token} whitelist
  • RBAC Check: Casbin enforcer verifies (user, path, method) tuple against policies
  • Async Logging: Opera logs queued to OperaLogQueue for background persistence
  • Response Encoding: Custom JSON encoders for datetime, UUID, Enum types

Example Log Output:

[2025-01-15 10:30:45.123] INFO [ctx.request_id=a1b2c3d4] GET /admin/v1/users/1
[2025-01-15 10:30:45.125] INFO [ctx.request_id=a1b2c3d4] JWT validated: user_id=1
[2025-01-15 10:30:45.127] INFO [ctx.request_id=a1b2c3d4] RBAC check: ALLOW
[2025-01-15 10:30:45.180] INFO [ctx.request_id=a1b2c3d4] Response: 200 OK (57ms)

See: Request Processing for detailed middleware documentation

Sources: backend/middleware/context_middleware.py backend/middleware/access_middleware.py backend/middleware/jwt_middleware.py backend/middleware/opera_log_middleware.py backend/common/security/jwt.py backend/common/security/rbac.py


Project Structure

FBA organizes code into clear layers that reflect the pseudo 3-tier architecture:

backend/
├── app/                    # Business applications
│   ├── admin/             # Core admin module (RBAC, users, roles)
│   │   ├── api/v1/        # API endpoints (presentation layer)
│   │   ├── schema/        # Pydantic request/response models
│   │   ├── service/       # Business logic layer
│   │   ├── crud/          # Data access layer
│   │   ├── model/         # SQLAlchemy ORM entities
│   │   └── conf/          # Configuration (RBAC model)
│   └── task/              # Celery task application
│       ├── api/v1/        # Task control endpoints
│       ├── service/       # Task execution logic
│       ├── scheduler.py   # DatabaseScheduler
│       └── celery.py      # Celery app config
├── cli/                   # CLI tool (fba commands)
│   ├── __main__.py        # Entry point
│   └── commands/          # Command implementations
├── common/                # Shared components
│   ├── security/          # JWT, RBAC dependencies
│   └── response/          # Response schemas
├── core/                  # Application core
│   ├── conf.py            # Settings (Pydantic)
│   └── registrar.py       # App registration
├── database/              # Database configuration
│   ├── db_postgres.py     # PostgreSQL setup
│   └── db_redis.py        # Redis client
├── middleware/            # Request processing pipeline
│   ├── context_middleware.py
│   ├── jwt_middleware.py
│   ├── opera_log_middleware.py
│   └── ...
├── plugin/                # Plugin system
│   ├── manager.py         # PluginManager
│   ├── dict/              # Dictionary plugin
│   ├── oauth2/            # OAuth2 social login
│   ├── code_gen/          # Code generator
│   └── email/             # Email service
├── utils/                 # Utility functions
│   ├── serializers.py     # Custom JSON encoders
│   └── timezone.py        # Timezone handling
└── main.py                # FastAPI app entry point

Design Principles:

  1. Layered Architecture: Clear separation between API, schema, service, CRUD, and model layers
  2. Dependency Injection: FastAPI dependencies manage authentication, database sessions, and permissions
  3. Async-First: All database and I/O operations use async/await
  4. Type Safety: Pydantic v2 validation, SQLAlchemy 2.0 type hints
  5. Modularity: Plugin system for feature extension without core changes
  6. Observability: Request tracing with ctx.request_id throughout the stack

Sources: Project directory structure, backend/main.py backend/core/registrar.py


Getting Started

To begin using FastAPI Best Architecture:

  1. Installation & Dependencies - See Installation & Dependencies for setup with uv package manager
  2. Configuration - See Configuration System for environment variables
  3. Running the Application - See Running the Application for starting the API server and Celery workers
  4. Docker Deployment - See Docker Deployment for production deployment with Docker Compose

For command-line operations, refer to the CLI Tool & Commands section.

Sources: README.md44-48 README.zh-CN.md42-44


Version History

The project is actively maintained with regular updates. Recent major milestones:

  • v1.10.2 (2025-10-21): Python 3.14 support, dependency updates
  • v1.10.0 (2025-10-17): PostgreSQL as primary database
  • v1.9.0 (2025-10-16): Context variables, service layer refactor
  • v1.8.0 (2025-08-15): Email plugin, i18n support
  • v1.7.0 (2025-07-16): Granian ASGI server, Celery dynamic tasks
  • v1.6.0 (2025-06-30): CLI tool introduction
  • v1.4.0 (2025-05-22): OAuth2 plugin system
  • v1.0.0 (2025-02-24): Initial release

For complete changelog, see CHANGELOG.md

Sources: CHANGELOG.md1-300