fastapi-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

FastAPI Best Practices

FastAPI 最佳实践

Comprehensive production-grade best practices for FastAPI applications. Contains rules across 7 categories to guide automated refactoring and code generation.
针对FastAPI应用的全面生产级最佳实践。包含多类规则,可指导自动化重构与代码生成。

When to Apply

适用场景

Reference these guidelines when:
  • Setting up a new FastAPI project structure
  • Implementing async routes and handling blocking I/O
  • Designing Pydantic models and validation logic
  • Structuring dependencies for reusable validation and injection
  • Integrating databases with SQLAlchemy and Alembic
  • Writing tests and configuring CI/CD tooling
以下场景可参考本指南:
  • 搭建新的FastAPI项目结构时
  • 实现异步路由并处理阻塞式I/O时
  • 设计Pydantic模型与验证逻辑时
  • 构建可复用验证与注入的依赖结构时
  • 通过SQLAlchemy和Alembic集成数据库时
  • 编写测试并配置CI/CD工具时

Rule Categories by Priority

按优先级划分的规则类别

PriorityCategoryImpactPrefix
1Async & ConcurrencyCRITICAL
async-
2Project StructureHIGH
structure-
3Pydantic PatternsHIGH
pydantic-
4Dependency InjectionMEDIUM-HIGH
dependency-
5Database & StorageMEDIUM
db-
6REST & API DesignMEDIUM
api-
7Testing & ToolingLOW-MEDIUM
tooling-
8Code MaintenanceLOW
maintenance-
9Performance OptimizationMEDIUM
performance-
10TDD StrategyHIGH
tdd-
优先级类别影响程度前缀
1异步与并发关键
async-
2项目结构
structure-
3Pydantic 模式
pydantic-
4依赖注入中高
dependency-
5数据库与存储
db-
6REST 与 API 设计
api-
7测试与工具中低
tooling-
8代码维护
maintenance-
9性能优化
performance-
10TDD 策略
tdd-

Quick Reference

快速参考

1. Async & Concurrency (CRITICAL)

1. 异步与并发(关键)

  • async-io-intensive
    - Use
    async def
    for awaitables,
    def
    for blocking I/O
  • async-cpu-intensive
    - Offload CPU work to multiprocessing/Celery
  • async-sync-sdk
    - Use
    run_in_threadpool
    for sync SDKs in async routes
  • async-io-intensive
    - 对可等待对象使用
    async def
    ,对阻塞式I/O使用
    def
  • async-cpu-intensive
    - 将CPU密集型工作卸载到多进程或Celery
  • async-sync-sdk
    - 在异步路由中使用
    run_in_threadpool
    处理同步SDK

2. Project Structure (HIGH)

2. 项目结构(高)

  • structure-domain-driven
    - Organize by domain (
    src/{domain}
    ), not file type
  • structure-domain-driven
    - 按领域(
    src/{domain}
    )而非文件类型组织代码

3. Pydantic Patterns (HIGH)

3. Pydantic 模式(高)

  • pydantic-validation
    - Use built-in regex, enums, etc.
  • pydantic-custom-base
    - Use custom base model for global serialization
  • pydantic-config
    - Split BaseSettings by domain
  • pydantic-value-error
    - Raise ValueError for validation errors
  • pydantic-validation
    - 使用内置的正则表达式、枚举等
  • pydantic-custom-base
    - 使用自定义基础模型实现全局序列化
  • pydantic-config
    - 按领域拆分BaseSettings
  • pydantic-value-error
    - 验证错误时抛出ValueError

4. Dependency Injection (MEDIUM-HIGH)

4. 依赖注入(中高)

  • dependency-validation
    - Use Depends for DB-backed validation
  • dependency-chaining
    - Chain dependencies for reuse
  • dependency-decoupling
    - Decouple into small reusable units
  • dependency-async
    - Prefer async dependencies
  • dependency-validation
    - 使用Depends实现基于数据库的验证
  • dependency-chaining
    - 链式调用依赖以实现复用
  • dependency-decoupling
    - 拆分为小型可复用单元
  • dependency-async
    - 优先使用异步依赖

5. Database & Storage (MEDIUM)

5. 数据库与存储(中)

  • db-naming-conventions
    - Strict naming (snake_case, singular, etc.)
  • db-index-naming
    - Explicit index naming conventions
  • db-sql-first
    - Prefer SQL for complex data logic
  • db-migrations
    - Static, descriptive, reversible migrations
  • db-naming-conventions
    - 严格遵循命名规范(蛇形命名、单数形式等)
  • db-index-naming
    - 明确的索引命名规范
  • db-sql-first
    - 复杂数据逻辑优先使用SQL
  • db-migrations
    - 静态、可描述、可回滚的迁移

6. REST & API Design (MEDIUM)

6. REST 与 API 设计(中)

  • api-path-naming
    - Consistent path vars for dependency reuse
  • api-response-serialization
    - Minimize serialization overhead
  • api-docs-hiding
    - Hide docs in production
  • api-docs-customization
    - Detailed OpenAPI metadata
  • api-path-naming
    - 统一路径变量以实现依赖复用
  • api-response-serialization
    - 最小化序列化开销
  • api-docs-hiding
    - 生产环境中隐藏文档
  • api-docs-customization
    - 详细的OpenAPI元数据

7. Testing & Tooling (LOW-MEDIUM)

7. 测试与工具(中低)

  • tooling-test-client
    - Use AsyncClient/httpx for tests
  • tooling-linter
    - Use Ruff for all linting
  • tooling-test-client
    - 使用AsyncClient/httpx进行测试
  • tooling-linter
    - 使用Ruff进行所有代码检查

8. New Capabilities (Merged)

8. 新功能(已合并)

  • Scripts: Helper scripts available in
    scripts/
    (e.g.,
    run_ruff.py
    ).
  • References: Additional guides in
    references/
    (e.g.,
    quad_strategy.md
    ).
  • TDD: Explicit testing strategies in
    rules/tdd-strategy.md
    .
  • 脚本
    scripts/
    目录下提供辅助脚本(如
    run_ruff.py
    )。
  • 参考资料
    references/
    目录下提供额外指南(如
    quad_strategy.md
    )。
  • TDD
    rules/tdd-strategy.md
    中包含明确的测试策略。

How to Use

使用方法

Read individual rule files for detailed explanations and code examples:
rules/async-io-intensive.md
rules/structure-domain-driven.md
阅读单个规则文件以获取详细说明和代码示例:
rules/async-io-intensive.md
rules/structure-domain-driven.md

Full Compiled Document

完整编译文档

For the complete guide with all rules expanded:
AGENTS.md
如需查看包含所有扩展规则的完整指南:
AGENTS.md