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.
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:
async/await syntaxKey Capabilities:
| Feature | Implementation |
|---|---|
| Authentication | JWT tokens with Redis whitelist via DepsJwtAuth |
| Authorization | Casbin RBAC with rbac_verify() and data scope filtering |
| Task Processing | Celery with database-driven scheduling and distributed locks |
| Plugin System | Hot-loadable modules via PluginManager.load_plugins() |
| Code Generation | Auto-generate CRUD operations from database schema |
| Logging | Request tracing with ctx.request_id, async audit logs |
| CLI Management | fba 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
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.
| Workflow | Java Equivalent | FBA Directory | Responsibility |
|---|---|---|---|
| View | Controller | api/ | Route definitions, HTTP handling |
| Data Transfer | DTO | schema/ | Request/response validation |
| Business Logic | Service + Impl | service/ | Business rules, orchestration |
| Data Access | DAO / Mapper | crud/ | Database query operations |
| Model | Model / Entity | model/ | 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)
Diagram: Data Flow Through 5-Layer Architecture
Architectural Rules:
DepsJwtAuth, DepsRBAC, and get_db() are injected at API layerschema classesfilter_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
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:
| Layer | Components | Key Files |
|---|---|---|
| Application Core | FastAPI app with pseudo 3-tier architecture | backend/main.py, backend/core/registrar.py |
| Presentation | API routes, middleware stack | backend/app/admin/api/, backend/middleware/ |
| Business Logic | Service classes, schemas | backend/app/admin/service/, backend/app/admin/schema/ |
| Data Access | CRUD operations, ORM models | backend/app/admin/crud/, backend/app/admin/model/ |
| Plugin System | Hot-loadable feature modules | backend/plugin/manager.py, backend/plugin/*/ |
| Task System | Celery distributed tasks | backend/app/task/celery.py, backend/app/task/scheduler.py |
| Storage | PostgreSQL, Redis, RabbitMQ | backend/database/db_postgres.py, backend/database/db_redis.py |
Data Flow:
backend/app/admin/api/v1/backend/app/admin/schema/Plugin Integration:
PluginManager.load_plugins() scans backend/plugin/ for plugin.toml filesAsync Tasks:
DatabaseScheduler reads sys_task table for dynamic Celery Beat scheduleshttp://localhost:8555Sources: 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
FBA provides five major feature categories that distinguish it as an enterprise backend solution:
Multi-layer security system:
rbac_verify()Key Components: DepsJwtAuth, DepsRBAC, filter_data_permission(), backend/common/security/
See: Authentication & Authorization
Hot-loadable architecture for feature extension:
Key Components: PluginManager, backend/plugin/manager.py, plugin.toml configuration
See: Plugin System
Dynamic Celery task management:
DatabaseScheduler replaces file-based beat schedule with database storageTzAwareCrontabKey Components: DatabaseScheduler, sys_task table, backend/app/task/scheduler.py
Multi-level observability system:
ctx.request_id) generated per request for correlationKey Components: ContextMiddleware, OperaLogQueue, backend/middleware/opera_log_middleware.py
See: Request Processing
Auto-generate CRUD scaffolding from database schema:
fba codegen import, fba codegen/code_gen/v1/preview for preview before generationKey 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
| Component | Library | Version | Purpose |
|---|---|---|---|
| Web Framework | FastAPI | Latest | Async API endpoints |
| ASGI Server | Granian | Latest | Production ASGI server |
| ORM | SQLAlchemy | 2.0+ | Async database toolkit |
| Validation | Pydantic | v2 | Data validation |
| Task Queue | Celery | Latest | Async task processing |
| Database | PostgreSQL | 16+ | Primary data store |
| Cache | Redis | Latest | Sessions, tokens, locks |
| Message Broker | RabbitMQ | Latest | Celery message queue |
| RBAC | Casbin | Latest | Permission policies |
| Logging | Loguru | Latest | Structured logs |
| Package Manager | uv | Latest | Fast dependency management |
| Code Quality | Ruff | Latest | Linting and formatting |
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 deploymentssnowflake_id_key(): Distributed snowflake IDs for horizontal scalingCore Tables:
sys_user: User accounts and profilessys_role: Role definitions and hierarchiessys_menu: Menu items and permissionssys_dept: Department/organization structuresys_data_scope: Data permission scopessys_data_rule: Row-level permission rulessys_opera_log: Operation audit logssys_login_log: Authentication audit trailsys_task: Celery task schedulesSee: Database Layer for detailed schema documentation
Five plugins are included by default in backend/plugin/:
| Plugin | Type | Route Prefix | Purpose |
|---|---|---|---|
| dict | App | /dict/v1 | Data dictionary (types and values) |
| oauth2 | Extend | /admin/v1/auth | Social login (GitHub, Google, LinuxDo) |
| config | App | /config/v1 | System configuration key-value store |
| App | /email/v1 | Email sending and verification codes | |
| code_gen | App | /code_gen/v1 | CRUD code generation from schema |
Plugin Types:
/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
Requests flow through multiple layers from client to database. The diagram below shows the complete processing pipeline.
Diagram: Request Processing Pipeline
Processing Stages:
| Stage | Middleware | Duration | Actions |
|---|---|---|---|
| 1. Context | context_middleware.py | <1ms | Generate ctx.request_id, parse ctx.trace_id |
| 2. Timing | access_middleware.py | <1ms | Record ctx.start_time |
| 3. I18n | i18n_middleware.py | <1ms | Parse Accept-Language to ctx.language |
| 4. Auth | jwt_middleware.py | 2-5ms | Decode JWT, check Redis whitelist |
| 5. RBAC | rbac_verify() dependency | 2-5ms | Verify Casbin policy |
| 6. State | state_middleware.py | 2-5ms | Parse IP location, user agent |
| 7. Routing | FastAPI router | <1ms | Match endpoint |
| 8. Business | Service layer | 10-50ms | Execute business logic |
| 9. Database | CRUD layer | 10-100ms | SQLAlchemy queries |
| 10. Logging | opera_log_middleware.py | <1ms | Queue operation log |
Key Processing Components:
ctx.request_id, ctx.trace_id, ctx.user, ctx.ip, ctx.language available throughout requestTOKEN_REDIS_PREFIX:{token} whitelist(user, path, method) tuple against policiesOperaLogQueue for background persistencedatetime, UUID, Enum typesExample 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
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:
async/awaitctx.request_id throughout the stackSources: Project directory structure, backend/main.py backend/core/registrar.py
To begin using FastAPI Best Architecture:
uv package managerFor command-line operations, refer to the CLI Tool & Commands section.
Sources: README.md44-48 README.zh-CN.md42-44
The project is actively maintained with regular updates. Recent major milestones:
For complete changelog, see CHANGELOG.md
Sources: CHANGELOG.md1-300
Refresh this wiki
This wiki was recently refreshed. Please wait 6 days to refresh again.