Vibe Coding
개발 아키텍처중급91% · 완성도 높음

Python FastAPI 비동기 백엔드 Vibe Coding 설정: Pydantic 계약 및 pytest 폐쇄 루프

중국어 로컬라이제이션을 위한 백엔드 아키텍처를 위한 완전한 Pydantic v2 계약, FastAPI 비동기 라우팅 및 pytest 자동화 검증 폐쇄 루프입니다.

예상 소요 시간: 60 min업데이트: 2026-11-26
Cursor IDEPython 3.12FastAPIPydantic v2pytest
Python FastAPI 비동기 백엔드 Vibe Coding 설정: Pydantic 계약 및 pytest 폐쇄 루프

완성도 점수

전체 완료도 91/100. 핵심 계약, 비동기 계층, 테스트 폐쇄 루프가 모두 구현되었으며, AI 생성 코드의 품질과 유지보수성이 높은 점수를 받았습니다. AI 는 모델, 라우팅, 테스트 생성 시 뛰어난 성능을 보였으나, 수동 검토를 통해 보안 헤더, 속도 제한 파라미터 및 예외 안전장치를 확인하는 것이 여전히 중요합니다.

91%완성도 높음

세부 항목 4가지

OpenAPI 및 Pydantic 계약95%

Schema-first 규칙은 모든 엔드포인트가 명시적인 Pydantic v2 모델을 갖도록 보장하여 95 점의 높은 계약 점수 요구사항에 부합합니다.

비동기 데이터베이스 트랜잭션 및 연결 풀90%

asyncpg 연결 풀과 비동기 세션을 사용하여 90 점의 비동기 DB 및 연결 관리 요구사항을 충족합니다.

pytest 자동화 검증 폐쇄 루프92%

100% 커버리지를 갖는 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
    이 엔드포인트에 대한 Pydantic v2 모델 블록을 생성하세요: POST /items, GET /items, PUT /items/{id}, DELETE /items/{id}. CreateItemRequest, ItemResponse, AuthUser 모델에 필수 필드, 타입 힌트 및 검증 제약조건 (ge, le, str) 을 포함하세요. YAML 프론트매터로 출력하세요.

    검증 기준: `vibe generate models` 를 실행하고 각 엔드포인트가 필수 필드와 타입 힌트를 갖는 모델 블록이 있는지 확인하세요.

  2. 2

    비동기 FastAPI 라우팅 및 의존성 주입 구축

    목표: async def 를 사용하여 모든 라우팅을 구현하고, FastAPI Depends 를 통해 DB 세션 및 인증을 주입합니다.

    Prompt
    네 개 엔드포인트에 대한 async def 핸들러를 갖는 FastAPI 앱을 작성하세요. 각 핸들러에 Depends([get_db_session(), get_current_user(api_key)]) 를 추가하세요. slowapi 를 사용하여 속도 제한을 적용하세요. 모든 I/O 가 await 되는지 확인하세요. 세션이 열리고 쿼리가 실행되며 닫히는지 확인하는 스모크 테스트로 검증하세요.

    검증 기준: `pytest tests/test_async_routes.py` 를 실행하고 모든 4 개 비동기 핸들러가 블로킹 없이 실행되며 DB 세션이 올바르게 닫히는지 확인하세요.

  3. 3

    pytest 비동기 테스트 폐쇄 루프 구축

    목표: 각 엔드포인트에 대해 성공, 오류, 검증, 속도 제한 시나리오를 커버하는 비동기 테스트를 작성하여 100% 분지 커버리지를 달성합니다.

    Prompt
    tests/ 디렉토리에 비동기 테스트를 생성하세요: test_create_item, test_list_items, test_update_item, test_delete_item, test_auth_and_rate_limit. pytest-asyncio, API_KEY 환경 변수를 위한 fixture 를 사용하고 올바른 상태 코드 및 Pydantic 검증 오류를 확인하세요. 커버리지를 실행하여 100% 분지 커버리지를 확인하세요.

    검증 기준: `pytest --cov-report=term-missing tests/` 를 실행하고 커버리지가 100% 분지 커버리지를 보이며 모든 테스트가 통과하는지 확인하세요.

  4. 4

    보안, 속도 제한 및 오류 안전장치 설정

    목표: X-API-Key 인증, 속도 제한, 구조화된 오류 처리 및 로그 출력을 설정하여 보안 폐쇄 루프를 완성합니다.

    Prompt
    X-API-Key 헤더 검증 미들웨어, 키별 slowapi 속도 제한, JSON 오류 스키마를 반환하는 사용자 정의 예외 처리기, 구조화된 JSON 로깅을 추가하세요. X-API-Key 없이 요청을 보내고 401 응답을 기대하여 검증하세요.

    검증 기준: X-API-Key 헤더 없이 요청을 보내고 JSON 오류 본문이 포함된 401 응답인지 확인하세요. 로그에 구조화된 JSON 엔TRIES 가 있는지 확인하세요.

흔한 함정과 해결책

  • 모든 라우팅에서 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 와 네이티브로 통합되어 사용이 간편하며 키별 카운팅을 지원합니다.

관련 플랜

Python FastAPI 비동기 백엔드 Vibe Coding 설정: Pydantic 계약 및 pytest 폐쇄 루프 · CursorHome