fastapi

FastAPI Defaults

Core FastAPI patterns and conventions

Python
framework
Default
Used by 1392 projects

Details

Language / Topic
pythonPython
Category
framework
Compatible Frameworks
fastapi

Rules

balanced
- Import FastAPI and create app instance: from fastapi import FastAPI; app = FastAPI()
- Define path operations as async functions with type hints and Pydantic models for request/response validation
- Use Field(..., description=...) in Pydantic models for automatic OpenAPI documentation
- Load environment variables early with load_dotenv() and access via os.getenv() in dependencies
- Provide clear docstrings on path operations and models for agent/tool usage guidance
- Define path operations with type hints: `@app.get('/users/{id}') async def get_user(id: int) -> User` — FastAPI generates OpenAPI docs automatically.
- Use Pydantic models for request/response: `class CreateUser(BaseModel): name: str; email: EmailStr` — validation happens before your code runs.
- Use `Depends()` for dependency injection: `async def get_user(db: Session = Depends(get_db))` — compose dependencies for auth, DB, and services.
- Use `BackgroundTasks` for fire-and-forget operations: `background_tasks.add_task(send_email, user.email)`.