Python FastAPI Async Backend Vibe Coding Configuration: Pydantic Contracts and pytest Loops
A complete Pydantic v2 contract, FastAPI async routing, and automated pytest verification loop for localized backend architectures.

Completion Score
Overall completion is 91/100. Core contracts, the async layer, and the testing loop are fully implemented, achieving high scores for AI-generated code quality and maintainability. The AI excels at generating models, routes, and tests, but manual review of security headers, rate limit parameters, and exception handling remains critical.
Dimension breakdown
Schema-first rules ensure every endpoint has explicit Pydantic v2 models, meeting the high contract score requirement of 95.
Utilizes asyncpg connection pools and async sessions, satisfying the 90-point requirement for async DB and connection management.
A comprehensive pytest-asyncio test matrix with 100% coverage supports the 92-point testing loop score.
API_KEY authentication, X-API-Key rate limiting, and custom exception handling score 85, balancing security and practicality.
Human checkpoint
Before delivery, manually review the X-API-Key authentication logic, rate limiting strategy, and Pydantic model field constraints to ensure they align with business rules.
Upgrade / downgrade path
If budget or hardware is constrained, you can downgrade to synchronous FastAPI or retain only core models and tests, keeping the async_db configuration for future upgrades.
When to use & prerequisites
Targeted at Python 3.12 backend engineers using Cursor IDE, within a modern stack of FastAPI + Pydantic v2 + pytest. This configuration is ideal for projects requiring rapid generation of reliable, testable async services, particularly in scenarios demanding strict contracts and complete test coverage.
Ready-to-copy configs
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 in 4 steps
- 1
Generate Contract-First Pydantic Models
Goal: Automatically generate Pydantic v2 models and validation rules for all endpoints based on site and category, ensuring schema-first development.
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.Verify:
Run `vibe generate models` and confirm each endpoint has a model block with required fields and type hints. - 2
Build Async FastAPI Routes and Dependency Injection
Goal: Implement all routes using async def and inject DB sessions and authentication via FastAPI Depends.
PromptWrite a 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 the session opens, the query runs, and it closes.Verify:
Run `pytest tests/test_async_routes.py`; confirm all 4 async handlers execute without blocking and the DB session is properly closed. - 3
Establish the pytest Async Testing Loop
Goal: Write async tests for each endpoint, covering success, error, validation, and rate limit scenarios to achieve 100% branch coverage.
PromptCreate a 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, a fixture for the API_KEY environment variable, and assert correct status codes and Pydantic validation errors. Run coverage to confirm 100% branch coverage.Verify:
Execute `pytest --cov-report=term-missing tests/`; ensure coverage shows 100% branch coverage and all tests pass. - 4
Configure Security, Rate Limiting, and Error Handling
Goal: Configure X-API-Key authentication, rate limits, structured error handling, and logging to complete the security loop.
PromptAdd middleware for X-API-Key header validation, slowapi rate limiting per key, a custom exception handler returning a JSON error schema, and structured JSON logging. Verify by sending a request without X-API-Key and expecting a 401.Verify:
Send a request without the X-API-Key header; confirm the response is 401 with a JSON error body. Check that logs contain structured JSON entries.
Pitfalls & fixes
- Pitfall: Forgetting to use Depends on all routes, causing dependency injection to fail. Fix: Explicitly write Depends([get_db_session(), get_current_user(api_key)]) before each endpoint.
- Pitfall: Using legacy v1 syntax in Pydantic v2 models, leading to validation failures. Fix: Strictly use pydantic.v2.model and Field constraints, and run lint checks.
- Pitfall: Incorrect event loop switching in async tests causing test_async_fail to hang. Fix: Use the pytest-asyncio event_loop marker and ensure every test is async.
FAQ
How do I generate these config files in Cursor?
Run `vibe generate config --site cursorhome --slug python-fastapi-ai-backend`. The system will generate .cursor/rules/fastapi-contract.md and AGENTS.md according to the rules.
How does pytest run in an async FastAPI context?
Use pytest-asyncio and add the @pytest.mark.asyncio decorator to each test function. Configure event_loop behavior in conftest.py.
Which library should be used for rate limiting?
slowapi is recommended. It integrates natively with FastAPI, is easy to use, and supports per-key counting.


