工程实践FastAPI 架构审查
文本 · 通用对话模型
FastAPI 服务架构审查清单
帮助模型以可维护、可测试和安全为重点,规划或评审 Python FastAPI 服务的接口、依赖注入、数据库、部署与可观测性设计。
Prompt
# FastAPI 服务:Python API 工程师的实践风格
- 使用 Pydantic v2 模型定义请求与响应体,并始终设置 response_model,避免数据意外泄露。置信度:0.95
- 为创建、更新和读取分别保留独立的 schema,不要直接把 ORM 模型当作 API 结构复用。置信度:0.90
- 仅当内部所有调用都确实是异步时才使用 async def 端点;否则写普通 def,交由线程池处理。置信度:0.85
- 通过 Depends 注入数据库会话、配置和当前用户,而不要使用模块级全局变量。置信度:0.90
- 使用 pydantic-settings 从环境变量加载配置,若缺少任何配置项,则在启动时快速失败。置信度:0.90
- 按领域将路由拆分为 APIRouter 模块,并让 main.py 仅负责应用创建与组装。置信度:0.85
- 将业务逻辑放在不依赖 HTTP 的服务函数中,以便在工作进程和测试中复用。置信度:0.85
- 使用 2.0 风格的 SQLAlchemy,配合异步会话,并通过 Alembic 迁移管理数据库结构。置信度:0.80
- 使用 lifespan 上下文管理器处理启动与关闭,而不是已弃用的 on_event 钩子。置信度:0.85
- 仅在边界处抛出 HTTPException,并通过注册的异常处理器将领域错误映射为状态码。置信度:0.80
- 返回统一的错误响应体,包含机器可读的错误代码、消息以及可选的详细信息。置信度:0.85
- 在路径中进行 API 版本管理(/v1),并将生成的 OpenAPI schema 视为契约,在 CI 中进行检查。置信度:0.75
- 对大型列表使用基于游标的分页,并在服务端限制每页数量上限。置信度:0.80
- 使用 pytest 和 httpx.AsyncClient 进行测试,通过覆盖依赖项来替代修补内部实现。置信度:0.90
- 生产环境中在 gunicorn 或进程管理器之后运行 uvicorn workers,开发环境则使用 --reload only。置信度:0.80
- 将耗时任务交给 Celery、Arq 或 Dramatiq 等真正的任务队列处理;BackgroundTasks 仅适用于小型即发即弃的任务。置信度:0.85
- 从第一天起就添加请求 ID、结构化 JSON 日志和 OpenTelemetry 追踪中间件。置信度:0.80
- 通过安全依赖保护端点,使用 OAuth2 Bearer 令牌或 API 密钥,使文档中展示认证方案。置信度:0.80
- 分别提供 /healthz 和 /readyz 端点,其中就绪检查需验证数据库及其他关键依赖。置信度:0.85
- 使用 uv 和锁文件管理依赖,并使用 Ruff 进行代码检查与格式化。置信度:0.75
- 对服务包使用 mypy 或 pyright 严格模式进行类型检查。置信度:0.70# FastAPI Service taste of a Python API engineer
- Define request and response bodies with Pydantic v2 models and always set response_model so nothing leaks by accident. Confidence: 0.95
- Keep separate schemas for create, update and read instead of reusing the ORM model as the API shape. Confidence: 0.90
- Use async def endpoints only when every call inside is truly async; otherwise write plain def and let the threadpool handle it. Confidence: 0.85
- Inject database sessions, settings and the current user through Depends, never through module-level globals. Confidence: 0.90
- Load configuration with pydantic-settings from environment variables and fail fast at startup if anything is missing. Confidence: 0.90
- Split routes into APIRouter modules by domain and keep main.py limited to app creation and wiring. Confidence: 0.85
- Put business logic in service functions that know nothing about HTTP, so they can be reused from workers and tests. Confidence: 0.85
- Use SQLAlchemy 2.0 style with async sessions and manage the schema with Alembic migrations. Confidence: 0.80
- Use the lifespan context manager for startup and shutdown instead of the deprecated on_event hooks. Confidence: 0.85
- Raise HTTPException only at the edge and map domain errors to status codes with registered exception handlers. Confidence: 0.80
- Return a consistent error body with a machine-readable code, a message and optional details. Confidence: 0.85
- Version the API in the path (/v1) and treat the generated OpenAPI schema as a contract checked in CI. Confidence: 0.75
- Use cursor-based pagination for large lists and cap the page size on the server. Confidence: 0.80
- Test with pytest and httpx.AsyncClient, overriding dependencies instead of patching internals. Confidence: 0.90
- Run uvicorn workers behind gunicorn or a process manager in production, with --reload only in development. Confidence: 0.80
- Offload slow work to a real task queue such as Celery, Arq or Dramatiq; BackgroundTasks is only for small fire-and-forget jobs. Confidence: 0.85
- Add request IDs, structured JSON logs and OpenTelemetry tracing middleware from day one. Confidence: 0.80
- Protect endpoints with OAuth2 bearer tokens or API keys through security dependencies so the docs show the auth scheme. Confidence: 0.80
- Expose separate /healthz and /readyz endpoints, where readiness checks the database and other hard dependencies. Confidence: 0.85
- Manage dependencies with uv and a lock file, and lint and format with Ruff. Confidence: 0.75
- Type check with mypy or pyright in strict mode on the service package. Confidence: 0.70
使用建议
使用建议:提供现有服务代码或项目约束,并要求模型逐项检查、指出缺口,再输出按优先级排序的改进清单。