Vibe Coding
開発アーキテクチャ中級91% · 高完成度

Python FastAPI 非同期バックエンド Vibe コーディング設定:Pydantic 契約と pytest 閉ループ

中国語ローカライズ向けバックエンドアーキテクチャの完全な Pydantic v2 契約、FastAPI 非同期ルート、および pytest 自動化検証閉ループ。

所要時間: 60 min更新日: 2026-11-26
Cursor IDEPython 3.12FastAPIPydantic v2pytest
Python FastAPI 非同期バックエンド Vibe コーディング設定:Pydantic 契約と pytest 閉ループ

完了度スコア

全体完了度 91/100。コア契約、非同期層、テスト閉ループがすべて実装済みです。AI 生成コードの品質と保守可能性は高スコアです。AI はモデル、ルート、テストの生成において優れていますが、セキュリティヘッダー、レート制限パラメータ、および例外フォールバックの手動レビューが依然として重要です。

91%高完成度

4つの評価軸

OpenAPI と Pydantic 契約95%

Schema-first ルールにより、すべてのエンドポイントに明確な Pydantic v2 モデルが存在し、95 点の高契約スコア要件に適合します。

非同期データベーストランザクションと接続プール90%

asyncpg 接続プールと非同期セッションを使用し、90 点の非同期 DB と接続管理要件を満たします。

pytest 自動化検証閉ループ92%

pytest-asyncio テストマトリックスで完全カバレッジを実現し、92 点のテスト閉ループスコアを支援します。

認証、レート制限、および例外フォールバック85%

API_KEY 認証、X-API-Key レート制限、およびカスタム例外処理により、85 点を獲得し、セキュリティと実用性を両立します。

人手確認ポイント

納品前に、X-API-Key 認証ロジック、レート制限戦略、および Pydantic モデルのフィールド制約がビジネスルールに適合しているか、人工的に確認してください。

アップグレード / ダウングレード経路

予算やハードウェアが制限されている場合、同期 FastAPI にダウングレードするか、コアモデルとテストのみを保持し、後続のアップグレードのために async_db 設定を保持できます。

適用場面と前提条件

ターゲットユーザーは Cursor IDE を使用している Python 3.12 バックエンドエンジニアです。環境は FastAPI + Pydantic v2 + pytest の現代スタックです。この設定は、信頼性が高くテスト可能な非同期サービスが迅速に生成される必要があるプロジェクトに適しています。特に厳格な契約と完全なテストカバレッジが求められるシナリオで有効です。

そのまま使える設定

.cursor/rules/fastapi-contract.mdmarkdown

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"
AGENTS.mdmarkdown

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 4ステップ

  1. 1

    契約優先の Pydantic モデルを生成

    目標: site と category に基づいて、すべてのエンドポイントの Pydantic v2 モデルと検証ルールを自動的に生成し、schema-first 開発を確保します。

    Prompt
    Generate 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. 2

    非同期 FastAPI ルートと依存性注入を構築

    目標: async def を使用してすべてのルートを実装し、FastAPI Depends を介して DB セッションと認証を注入します。

    Prompt
    Write 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 セッションが適切に閉じられていることを確認してください。

  3. 3

    pytest 非同期テスト閉ループを構築

    目標: 各エンドポイントに対して非同期テストを記述し、成功、エラー、検証、およびレート制限シナリオをカバーして、100% ブランチカバレッジを実現します。

    Prompt
    Create 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. 4

    セキュリティ、レート制限、およびエラーフォールバック設定

    目標: X-API-Key 認証、レート制限、構造化エラー処理、およびログ出力を設定し、セキュリティ閉ループを完了します。

    Prompt
    Add 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 エントリが含まれているか確認してください。

よくある落とし穴と対策

  • Pitfall: すべてのルートで Depends を使用することを忘れると、依存性注入が機能しません。Fix: 各 endpoint の前に明示的に Depends([get_db_session(), get_current_user(api_key)]) を記述してください。
  • Pitfall: Pydantic v2 モデルが旧版 v1 構文を使用すると検証が失敗します。Fix: 厳密に pydantic.v2.model と Field 制約を使用し、lint チェックを実行してください。
  • Pitfall: 非同期テストでイベントループを正しく切り替えないと test_async_fail がフリーズします。Fix: 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 カウントをサポートしています。

関連プラン

Python FastAPI 非同期バックエンド Vibe コーディング設定:Pydantic 契約と pytest 閉ループ · CursorHome