This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: fastapi-pydantic-v2

FastAPI & Pydantic v2 Async Concurrency Standard

Guardrails for FastAPI with Pydantic v2: prevent synchronous blocking calls inside async def endpoints, use lifespan context managers, and migrate to model_dump().

Prohibited Anti-Pattern: AI calls blocking synchronous requests.get() or time.sleep() inside async def, freezing the entire event loop.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FastAPI & Pydantic v2 Async Concurrency Standard - Guardrails for FastAPI with Pydantic v2: prevent synchronous blocking calls inside async def endpoints, use lifespan context managers, and migrate to model_dump().
globs: app/**/*.py, src/**/*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fastapi-pydantic-v2"
---

# FastAPI & Pydantic v2 Async Concurrency Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: AI calls blocking synchronous requests.get() or time.sleep() inside async def, freezing the entire event loop.

## System Constraints
You are a senior Python backend architect specializing in FastAPI and Pydantic v2. Never run blocking synchronous I/O (like requests.get, time.sleep, or sync DB drivers) inside async def routes. Use httpx.AsyncClient or asyncio.sleep. In Pydantic v2, use model_dump() and model_validate() instead of deprecated .dict() and .from_orm(). Use the Lifespan protocol for startup/shutdown.

## Strict Guidelines
- Do NOT call blocking I/O functions in 'async def'. If a library is strictly synchronous, either run it in regular 'def' (FastAPI executes it in a threadpool) or use anyio.to_thread.run_sync.
- Pydantic v2 deprecated .dict(), .json(), and .from_orm(); always use .model_dump(), .model_dump_json(), and .model_validate().
- Replace deprecated @app.on_event('startup') with the asynccontextmanager Lifespan handler.
- Always define response_model or explicit return types on FastAPI route decorators for automatic schema generation.

## Bad vs Good Implementations
### Non-blocking Async HTTP Request vs Blocking requests.get

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Calling sync requests.get inside async def blocks the main thread, stalling all other concurrent client requests.
```python
# CRITICAL FLAW: Blocking synchronous call in async def
from fastapi import FastAPI
import requests # Sync library!

app = FastAPI()

@app.get("/fetch")
async def fetch_data():
    # Freezes the entire asyncio event loop for all concurrent users!
    res = requests.get("https://api.external.com/data")
    return res.json()
```

#### Production Standard (Correct)
> **Standard**: httpx.AsyncClient releases the event loop during network I/O, allowing thousands of concurrent requests.
```python
# Production Standard: httpx.AsyncClient or non-async def
from fastapi import FastAPI
import httpx

app = FastAPI()

@app.get("/fetch")
async def fetch_data():
    async with httpx.AsyncClient(timeout=10.0) as client:
        res = await client.get("https://api.external.com/data")
        res.raise_for_status()
        return res.json()
```

### Pydantic v2 model_dump vs Deprecated .dict()

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Pydantic v2 throws deprecation warnings and performance penalties when calling v1 .dict().
```python
# Deprecated Pydantic v1 methods
from pydantic import BaseModel

class UserSchema(BaseModel):
    name: string

user = UserSchema(name="Bob")
payload = user.dict() # Triggers deprecation warning in v2!
```

#### Production Standard (Correct)
> **Standard**: Uses standard Pydantic v2 model_dump and ConfigDict(from_attributes=True).
```python
# Modern Pydantic v2 API
from pydantic import BaseModel, ConfigDict

class UserSchema(BaseModel):
    model_config = ConfigDict(from_attributes=True)
    name: str

user = UserSchema(name="Bob")
payload = user.model_dump(exclude_unset=True)
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: FastAPI & Pydantic v2 Async Concurrency Standard

FastAPI combined with Pydantic v2 offers unmatched serialization speed and strong typing in Python microservices. However, misconfigured asynchronous endpoints can easily starve the ASGI event loop. Calling synchronous I/O functions (such as legacy blocking SQLAlchemy queries or requests.get) inside `async def` endpoints blocks the entire Python process from handling other concurrent requests.

Framework Paradigm Shift & Drift MechanicsLLMs frequently mix sync and async libraries in Python. When asked for database code, AI models often import `sessionmaker` without `AsyncSession`, or use synchronous `time.sleep` / `requests` inside `async def` route handlers, turning an asynchronous server into a single-threaded bottleneck.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
Event Loop Thread BlockadeAI calls synchronous blocking DB or HTTP methods inside an `async def` endpointCritical
Paralyzes Uvicorn's asyncio event loop, causing server-wide request timeouts and 504 Gateway errors under concurrent traffic.
Either use pure `AsyncSession` with `await session.execute(...)`, or declare the route as standard synchronous `def` so FastAPI executes it in an external threadpool.
Pydantic v1 Legacy API HallucinationAI writes `class Config:` or `@validator` instead of `model_config` and `@field_validator`Medium
Triggers deprecation warnings in Pydantic v2 and breaks custom validator execution logic.
Use Pydantic v2 conventions: `@field_validator` with `@classmethod`, and `ConfigDict` for model configuration.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Do NOT call blocking I/O functions in 'async def'. If a library is strictly synchronous, either run it in regular 'def' (FastAPI executes it in a threadpool) or use anyio.to_thread.run_sync.

Do NOT call blocking I/O functions in 'async def'. If a library is strictly synchronous, either run it in regular 'def' (FastAPI executes it in a threadpool) or use anyio.to_thread.run_sync.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Pydantic v2 deprecated .dict(), .json(), and .from_orm()

Pydantic v2 deprecated .dict(), .json(), and .from_orm(); always use .model_dump(), .model_dump_json(), and .model_validate().

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Replace deprecated @app.on_event('startup') with the asynccontextmanager Lifespan handler.

Replace deprecated @app.on_event('startup') with the asynccontextmanager Lifespan handler.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Always define response_model or explicit return types on FastAPI route decorators for automatic schema generation.

Always define response_model or explicit return types on FastAPI route decorators for automatic schema generation.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:What is the difference between def and async def in FastAPI?

If you define a route with `async def`, FastAPI runs it directly on the main asyncio event loop; any blocking call will freeze the entire server. If you define it with `def`, FastAPI runs it in an external worker threadpool, allowing synchronous blocking operations without halting other requests.

Q:How do I upgrade Pydantic v1 schemas to Pydantic v2 in FastAPI?

Replace `class Config:` with `model_config = ConfigDict(...)`, change `@validator` to `@field_validator`, and use `.model_dump()` instead of `.dict()`.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

FastAPI