Python FastAPI Best Practices
Expert Python development rules for building production-grade FastAPI applications with modern tooling and best practices.
Stack & Tools
You MUST use the following stack:
**Python Version**: 3.12**Web Framework**: FastAPI**ORM**: SQLAlchemy**Validation**: Pydantic**Package Manager**: Poetry**Migrations**: Alembic**User Management**: fastapi-users**Authentication**: fastapi-jwt-auth**Email**: fastapi-mail**Caching**: fastapi-cache**Rate Limiting**: fastapi-limiter**Pagination**: fastapi-paginationCore Development Rules
1. Use Meaningful Names
Choose descriptive variable, function, and class namesNames should clearly communicate purpose and intentAvoid single-letter variables except in list comprehensions or mathematical contexts2. Follow PEP 8
Adhere strictly to the Python Enhancement Proposal 8 style guideUse 4 spaces for indentation (never tabs)Limit lines to 79 characters for code, 72 for docstringsUse snake_case for functions and variablesUse PascalCase for classes3. Use Docstrings
Document all functions, classes, and modules with docstringsExplain the purpose, parameters, return values, and exceptionsUse Google or NumPy docstring format consistently```python
def calculate_total(items: list[float], tax_rate: float) -> float:
"""Calculate the total price including tax.
Args:
items: List of item prices
tax_rate: Tax rate as a decimal (e.g., 0.08 for 8%)
Returns:
Total price including tax
Raises:
ValueError: If tax_rate is negative
"""
pass
```
4. Keep It Simple
Write simple and clear codeAvoid unnecessary complexity and clever tricksPrefer explicit over implicitBreak complex functions into smaller, single-purpose functions5. Use List Comprehensions
Prefer list comprehensions for creating lists over traditional loops when appropriateKeep comprehensions simple and readableUse generator expressions for large datasets```python
Good
squares = [x**2 for x in range(10)]
Avoid overly complex comprehensions
If it spans multiple lines, use a regular loop
```
6. Handle Exceptions
Use try-except blocks to handle exceptions gracefullyCatch specific exceptions, not bare `except:`Provide meaningful error messagesUse FastAPI's HTTPException for API errors```python
from fastapi import HTTPException
try:
result = await database.fetch_user(user_id)
except UserNotFoundError:
raise HTTPException(status_code=404, detail="User not found")
```
7. Use Virtual Environments
Always isolate project dependencies using virtual environmentsUse Poetry for dependency management (already specified in stack)Never install packages globally for project work8. Write Tests
Implement unit tests for all business logicUse pytest for testingAim for high test coverageTest edge cases and error conditionsUse FastAPI's TestClient for API endpoint testing```python
from fastapi.testclient import TestClient
def test_create_user(client: TestClient):
response = client.post("/users", json={"email": "[email protected]"})
assert response.status_code == 201
```
9. Use Type Hints
Utilize type hints for all function signaturesUse modern Python 3.12 type syntax (e.g., `list[str]` instead of `List[str]`)Leverage Pydantic models for request/response validationRun type checkers (mypy) in CI/CD```python
def process_items(items: list[dict[str, Any]]) -> dict[str, int]:
"""Process items and return summary statistics."""
pass
```
10. Avoid Global Variables
Limit the use of global variables to reduce side effectsUse dependency injection (FastAPI's `Depends`) for shared stateUse environment variables for configurationPrefer function parameters over global state```python
from fastapi import Depends
def get_db() -> DatabaseSession:
"""Dependency for database session."""
pass
@app.get("/users")
async def list_users(db: DatabaseSession = Depends(get_db)):
return await db.fetch_all_users()
```
FastAPI-Specific Patterns
Use async/await for I/O-bound operationsLeverage Pydantic models for request validationUse dependency injection for shared resourcesImplement proper error handling with HTTPExceptionUse SQLAlchemy's async engine for database operationsConfigure CORS, rate limiting, and caching appropriatelyStructure projects with routers for different API domainsWhen to Apply
Apply these rules when:
Building REST APIs with FastAPIDeveloping Python 3.12 applicationsWorking with SQLAlchemy and PydanticSetting up new FastAPI projectsReviewing or refactoring existing Python code