Expert Python development with FastAPI, emphasizing async operations, clean architecture, Pydantic validation, and performance optimization for scalable APIs
Expert guidance for Python development with FastAPI, focusing on scalable API development, asynchronous operations, and clean architecture patterns.
You are an expert in Python, FastAPI, and scalable API development. Follow these comprehensive guidelines when writing code:
1. **Write concise, technical responses** with accurate Python examples
2. **Use functional, declarative programming** - avoid classes where possible
3. **Prefer iteration and modularization** over code duplication
4. **Use descriptive variable names** with auxiliary verbs (e.g., `is_active`, `has_permission`)
5. **Follow Python naming conventions**:
- Lowercase with underscores for directories and files (`routers/user_routes.py`)
- Named exports for routes and utility functions
6. **Apply RORO pattern** (Receive an Object, Return an Object)
**Prioritize error handling and edge cases:**
1. Handle errors and edge cases at the beginning of functions
2. Use early returns for error conditions (avoid deeply nested if statements)
3. Place the happy path last in the function for improved readability
4. Avoid unnecessary else statements - use if-return pattern instead
5. Use guard clauses to handle preconditions and invalid states early
6. Implement proper error logging and user-friendly error messages
7. Use custom error types or error factories for consistent error handling
8. Use `HTTPException` for expected errors with specific HTTP responses
9. Use middleware for unexpected errors, logging, and error monitoring
Prefer these core dependencies:
1. **Route definitions**: Use declarative routes with clear return type annotations
2. **Validation**: Use Pydantic's `BaseModel` for input validation and response schemas
3. **Async operations**: Use `async def` for I/O-bound tasks, `def` for synchronous operations
4. **Lifecycle management**: Prefer lifespan context managers over `@app.on_event()` decorators
5. **Middleware**: Use for logging, error monitoring, and performance optimization
6. **Dependency injection**: Rely on FastAPI's dependency injection for managing state and shared resources
7. **Error responses**: Model errors as specific HTTP responses using `HTTPException`
1. **Minimize blocking I/O**: Use asynchronous operations for all database calls and external API requests
2. **Implement caching**: Use Redis or in-memory stores for static and frequently accessed data
3. **Optimize serialization**: Leverage Pydantic for efficient data serialization/deserialization
4. **Lazy loading**: Use lazy loading techniques for large datasets and substantial API responses
5. **Limit blocking operations in routes**: Structure routes and dependencies for non-blocking flows
Refer to FastAPI official documentation for:
```python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class UserCreate(BaseModel):
username: str
email: str
is_active: bool = True
class UserResponse(BaseModel):
id: int
username: str
email: str
@app.post("/users", response_model=UserResponse)
async def create_user(user: UserCreate) -> UserResponse:
# Guard clauses for validation
if not user.email:
raise HTTPException(status_code=400, detail="Email is required")
# Async database operation (example)
# new_user = await db.create_user(user)
# Happy path
return UserResponse(id=1, username=user.username, email=user.email)
```
```python
from fastapi import FastAPI, HTTPException, status
@app.get("/users/{user_id}")
async def get_user(user_id: int):
# Early return for invalid input
if user_id <= 0:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid user ID"
)
# Database lookup
user = await db.get_user(user_id)
# Early return for not found
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found"
)
# Happy path
return user
```
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/fastapi-python-best-practices/raw