Files
zhixing-system/.trellis/spec/backend/http-api-contracts.md
T
2026-08-04 18:59:21 +08:00

31 lines
1.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# HTTP API 契约
## 路由组合
`zhixing-server/src/zhixing_server/interfaces/http/router.py` 是 `/api/v1` 的唯一目录入口:
```python
api_v1_router = APIRouter(prefix="/api/v1")
api_v1_router.include_router(system_router, prefix="/system", tags=["system"])
```
跨上下文的运维端点放在 `operational_router`;业务端点应由对应上下文的 presentation 适配器提供,再由路由目录挂载。不要在 `bootstrap/app.py` 里堆积路径字符串。
## 响应模型
每个稳定的 JSON 响应都应有 Pydantic `BaseModel`,并在装饰器中声明 `response_model`。现有 `HealthResponse` 和 `SystemStatusResponse` 位于 `interfaces/http/system.py`:
- `/healthz` 返回严格的 `{"status": "ok"}`,设置 `include_in_schema=False` 以供容器探针使用。
- `/api/v1/system/status` 返回 `status`、`service`、`environment`;只暴露安全的运行时元数据,不返回环境变量原文或秘密。
- 字段名是前后端契约的一部分。变更时同步更新 `zhixing-server/tests/test_system_http.py`、`zhixing-web/src/features/system/api/system.types.ts` 和页面测试。
## 输入、依赖和错误
- 通过 FastAPI 参数、`Annotated` 依赖和 Pydantic 模型完成边界转换;不要把原始请求对象传入 domain。
- 简单、无阻塞的当前端点使用同步 `def`,保持与 `system.py` 一致;只有实际需要异步 I/O 时才使用 `async def`。
- 当前服务没有自定义错误 envelope。验证错误和显式 HTTP 错误沿用 FastAPI 默认契约,除非先增加全局约定并补充测试。
## 验证
后端契约用 `TestClient(create_app())` 测试,参照 `tests/test_system_http.py`。前端使用同源 `/api/v1/...` 路径,经 `shared/api/request-json.ts` 调用;不要在 feature 页面内直接调用 `fetch`。