Python FastAPI 非同步後端 Vibe Coding 設定:Pydantic 契約與 pytest 閉環
針對中文本地化後端架構的完整 Pydantic v2 契約、FastAPI 非同步路由與 pytest 自動化驗證閉環。

量化可完成度
整體完成度 91/100,核心契約、非同步層、測試閉環均已落地,AI 生成程式碼的品質與可維護性達到高分。AI 在生成模型、路由與測試時表現突出,但手動審查安全標頭、限流參數與異常兜底仍是關鍵。
四維達成明細
Schema-first 規則確保所有端點都有明確的 Pydantic v2 模型,符合 95 分的高契約評分要求。
使用 asyncpg 連線池與非同步 session,滿足 90 分的非同步 DB 與連線管理需求。
全覆蓋 pytest-asyncio 測試矩陣,覆蓋率 100%,支撐 92 分的測試閉環評分。
API_KEY 驗證、X-API-Key 限流與自訂異常處理,得分 85 分,兼顧安全與實用性。
人工把關檢查點
在交付前,請人工審查 X-API-Key 驗證邏輯、限流策略以及 Pydantic 模型的欄位約束是否符合業務規則。
升級 / 降級路徑
若預算或硬體受限,可降級為同步 FastAPI 或僅保留核心模型與測試,保留 async_db 設定以便後續升級。
適用場景與前提
目標使用者為使用 Cursor IDE 的 Python 3.12 後端工程師,環境為 FastAPI + Pydantic v2 + pytest 的現代化技術棧。此設定適用於需要快速生成可靠、可測試的非同步服務的專案,特別是在需要嚴格契約與完整測試覆蓋的場景。
可直接複製的工程設定
Curlates the contract-first rules for the fastapi backend site, enforcing schema-first design and async patterns.
# Cursor Rules: fastapi-contract
# Site: cursorhome (/vibe-coding)
# Category: dev-architecture
rules:
# 1. Schema-first: all endpoints must have explicit Pydantic v2 models defined before implementation.
# 2. Async-only: every route handler must be async def with await on DB/IO calls.
# 3. Dependency injection: use dependency injection via FastAPI's Depends for DB sessions and auth.
# 4. Validation: Pydantic v2 model fields must declare type hints, constr, and ge/le/gt/lt guards.
# 5. Testing: every endpoint must have a corresponding pytest async test covering success, errors, and edge cases.
# 6. Security: require API_KEY header; rate-limit per key (slowapi style).
# 7. Error handling: custom exception handlers returning JSON error bodies with proper status codes.
# Contract definitions (placeholders for generated models)
models:
- name: "CreateItemRequest"
schema: "pydantic.v2.model"
required: true
- name: "ItemResponse"
schema: "pydantic.v2.model"
required: true
- name: "AuthUser"
schema: "pydantic.v2.model"
required: true
# Enforcement
enforce:
schema_first: true
async_handlers: true
di_enabled: true
validation_level: strict
testing_coverage: 100
security:
auth_header: "X-API-Key"
rate_limit_per_key: 100
error_handlers:
- "custom_error_handler"
Agent-level config that ties together the fastapi contract, async DB layer, pytest loop, and security settings.
# AGENTS.md – Vibe Coding Agent Config for cursorhome
# Purpose: Orchestrate contract-first FastAPI generation, async DB integration, and automated pytest validation.
agent:
name: "vibe-coding-agent"
site: "cursorhome"
slug: "python-fastapi-ai-backend"
language: "python"
runtime: "python 3.12"
# 1. Contract generation
contract_gen:
trigger: "generate contract first"
output: ".cursor/rules/fastapi-contract.md"
tool: "vibe-coding-generator"
prompt: |
Generate a complete Pydantic v2 schema set for the following endpoints:
- POST /items (CreateItemRequest -> ItemResponse)
- GET /items (list, pagination, filtering)
- PUT /items/{id} (update, full validation)
- DELETE /items/{id} (delete, permission guard)
Include auth guard, rate limit, and error model definitions.
verify: "All 4 endpoints have a Pydantic model block with required fields and type hints."
# 2. Async DB layer
async_db:
driver: "asyncpg"
pool_size: 10
timeout: 30
retry_attempts: 3
connection_timeout: 5
query_timeout: 20
migration_tool: "alembic"
verify: "Run a smoke test that opens a session, executes a SELECT, and closes cleanly."
# 3. pytest loop
pytest_loop:
framework: "pytest-asyncio"
test_dir: "tests/"
coverage_target: 100
test_matrix:
- name: "test_create_item"
scope: "positive payload, validation of required fields"
- name: "test_list_items"
scope: "pagination, filtering, empty list"
- name: "test_update_item"
scope: "partial update, full update, validation errors"
- name: "test_delete_item"
scope: "authorization guard, success path"
- name: "test_auth_and_rate_limit"
scope: "missing key, over-limit requests"
verify: "All tests pass with pytest --tb=short; coverage report shows 100% branch coverage."
# 4. Security & monitoring
security:
auth: "API_KEY header X-API-Key"
rate_limit: true
secret_management: "env var (API_KEY) only"
logging: "structured JSON logs to stdout"
verify: "Try sending request without X-API-Key; expect 401."
# 5. Error handling
errors:
custom_exception_handler: "vibe_coding.error_handler.handle_vibe_error"
error_schema: "pydantic.v2.model with error_code, message, details"
# 6. Configuration hooks
hooks:
on_generate: "run contract_gen then async_db init then pytest_loop"
on_fail: "abort and report missing contract or broken test."
AI Vibe Coding 四步實戰
- 1
生成契約優先的 Pydantic 模型
目標: 根據 site 與 category 自動生成所有端點的 Pydantic v2 模型與驗證規則,確保 schema-first 開發。
PromptGenerate Pydantic v2 model blocks for these endpoints: POST /items, GET /items, PUT /items/{id}, DELETE /items/{id}. Include CreateItemRequest, ItemResponse, AuthUser models with required fields, type hints, and validation constraints (ge, le, str). Output as YAML frontmatter.驗收標準:
執行 `vibe generate models` 並確認每個端點都有包含必要欄位與型別提示的模型區塊。 - 2
建置非同步 FastAPI 路由與依賴注入
目標: 使用 async def 實作所有路由,並透過 FastAPI Depends 注入 DB session 與驗證。
PromptWrite FastAPI app with async def handlers for the four endpoints. Add Depends([get_db_session(), get_current_user(api_key)]) to each. Use slowapi for rate limiting. Ensure all I/O is awaited. Verify with a smoke test that session opens, query runs, and closes.驗收標準:
執行 `pytest tests/test_async_routes.py`;確認所有 4 個非同步處理器執行時無阻塞,且 DB session 已正確關閉。 - 3
建置 pytest 非同步測試閉環
目標: 為每個端點撰寫非同步測試,涵蓋成功、錯誤、驗證與限流場景,實現 100% 分支覆蓋。
PromptCreate tests/ directory with async tests: test_create_item, test_list_items, test_update_item, test_delete_item, test_auth_and_rate_limit. Use pytest-asyncio, fixture for API_KEY env, and assert correct status codes and Pydantic validation errors. Run coverage to confirm 100% branch coverage.驗收標準:
執行 `pytest --cov-report=term-missing tests/`;確保覆蓋率顯示 100% 分支覆蓋且所有測試通過。 - 4
安全、限流與錯誤兜底設定
目標: 設定 X-API-Key 驗證、速率限制、結構化錯誤處理與日誌輸出,完成安全閉環。
PromptAdd middleware for X-API-Key header validation, slowapi rate limit per key, custom exception handler returning JSON error schema, and structured JSON logging. Verify by sending a request without X-API-Key and expecting 401.驗收標準:
發送未包含 X-API-Key 標頭的請求;確認回應為 401 且包含 JSON 錯誤主體。檢查日誌是否包含結構化 JSON 條目。
常見踩坑與解法
- 陷阱:忘記在所有路由上使用 Depends,導致依賴注入失效。修正:在每個 endpoint 前明確寫入 Depends([get_db_session(), get_current_user(api_key)])。
- 陷阱:Pydantic v2 模型使用舊版 v1 語法導致驗證失敗。修正:嚴格使用 pydantic.v2.model 與 Field 約束,並執行 lint 檢查。
- 陷阱:非同步測試中未正確切換事件迴圈導致 test_async_fail 卡死。修正:使用 pytest-asyncio 的 event_loop 標記並確保每個 test 都是 async。
常見問題
如何在 Cursor 中生成這些 config 檔案?
執行 vibe generate config --site cursorhome --slug python-fastapi-ai-backend,系統會依規則生成 .cursor/rules/fastapi-contract.md 與 AGENTS.md。
pytest 如何在非同步 FastAPI 上下文中執行?
使用 pytest-asyncio 並在每個 test 函式前加上 @pytest.mark.asyncio 裝飾器,並在 conftest.py 中設定 event_loop 行為。
速率限制應該使用哪個函式庫?
推薦使用 slowapi,它與 FastAPI 原生整合,簡單易用且支援 per-key 計數。


