1---2name: fastapi3description: FastAPI endpoint design, Pydantic validation, dependency injection, and async patterns4---56## FastAPI Code Review Rules78### Security (Critical)9- **Input Validation**: Apply strict type, length, and format checks to all user-supplied input. Sanitize inputs using trusted libraries before any rendering or database operation10- **Template Variable Safety**: Never render unvalidated template variables (`{{ ... }}`), and always declare variable sources. Avoid HTML comments (`<!-- -->`) as they may expose sensitive info or facilitate injection attacks11- **Comment Hygiene**: Never use HTML comments in production code to store data or instructions12- Use `OAuth2PasswordBearer` or similar for auth13- Rate limit sensitive endpoints14- Never log sensitive data (passwords, tokens)15- Implement CORS properly with `CORSMiddleware`16- Use CSRF protection for cookie-based auth17- Validate content types and sanitize HTML to prevent XSS18- Use security headers (HSTS, CSP, X-Frame-Options)19- Always validate user input in path operations and request bodies2021### Endpoint Design (Essential)22- Use appropriate HTTP methods (GET for reads, POST for creates, etc.)23- Return appropriate status codes (201 for create, 204 for delete, etc.)24- Use path parameters for resource identifiers, query params for filtering25- Group related endpoints with `APIRouter` and tags26- Document endpoints with clear docstrings2728### Endpoint Design (Advanced)29- Use OpenAPI metadata (summary, description, response descriptions)30- Provide detailed response model documentation31- Implement API versioning (URL prefix recommended)32- Mark deprecated endpoints with `deprecated=True`3334### Pydantic Models (Essential)35- Use Pydantic models for request body validation (not raw dicts)36- Define explicit response models with `response_model` parameter37- Use `Field()` for validation constraints (min/max, regex, etc.)38- Separate input models from output models (Create vs Response)39- Use type annotations for all endpoint arguments and return types40- Return only JSON-serializable results41- Use `model_config` for Pydantic v2 configuration4243### Dependency Injection44- Use `Depends()` for shared logic (auth, db sessions, etc.)45- Database sessions should be dependencies, not global46- Close resources properly (use context managers or finally)4748### Async (Essential)49- Use `async def` for I/O-bound endpoints50- Don't mix sync and async database calls51- Use `asyncio.gather()` for parallel async operations52- Avoid blocking calls in async functions (use `run_in_executor`)5354### Async (Advanced)55- Use async context managers (`async with`) for managing async resources (DB sessions, HTTP clients)56- Use `BackgroundTasks` for work that should outlive the response57- Use startup/shutdown events (`@app.on_event("startup"/"shutdown")`) to initialize/cleanup shared async resources58- Apply concurrency limits with `asyncio.Semaphore` when calling external services59- For streaming responses or WebSockets, implement backpressure-aware designs60- For more patterns, see [FastAPI Async Documentation](https://fastapi.tiangolo.com/async/)6162### Error Handling63- Use `HTTPException` for expected errors with proper status codes64- Create custom exception handlers for domain exceptions65- Don't expose internal error details to clients66- Log errors with context (request ID, user, etc.)6768### Project Structure69- Organize by feature or layer (routers, models, services, dependencies)70- Keep routers thin - business logic in services71- Separate Pydantic models from database models72- Use a `dependencies` module for reusable dependencies73- Create `config.py` for settings management