---
title: FastAPI Best Practices
type: agent/instruction
tags: [fastapi, python, api]
---

{{h1}}FastAPI

{{h2}}Structure
- Organise by feature
- Separate routers, schemas, services
- Dependency injection
- APIRouter for modularity

{{h2}}Type Hints
- Pydantic models for request/response
- Type all parameters and returns
- `Field` for constraints
- Automatic validation

{{h2}}Async
- `async def` for I/O-bound
- Regular `def` for CPU-bound
- Async database drivers
- Don't mix blocking and async

{{h2}}Dependencies
- `Depends()` for reusable logic
- Auth as dependencies
- Database sessions via dependencies
- Override for testing

{{h2}}Request/Response
- Pydantic for validation
- Explicit response models
- `status` module for codes
- `response_model` to filter output

{{h2}}Error Handling
- `HTTPException` for API errors
- Custom exception handlers
- Consistent error responses

{{h2}}Database
- Async drivers (asyncpg, motor)
- Connection pooling
- SQLAlchemy 2.0 async
- Transactions for integrity

{{h2}}Security
- OAuth2 with JWT
- HTTPS in production
- Rate limiting
- CORS middleware

{{h2}}Performance
- Async for I/O
- Caching
- Background tasks for long ops
- Gzip compression

{{h2}}Avoid
- Don't use `async` unnecessarily
- Don't ignore type hints
- Don't return raw DB models
- Don't block event loop
