Expert guidance for Python FastAPI development with focus on async operations, type safety, and scalable API design following best practices.
Expert guidance for building scalable, high-performance APIs with Python and FastAPI. This skill enforces best practices for async operations, type safety, error handling, and API design patterns.
Provides comprehensive Python/FastAPI development guidance covering:
1. **Code Style**
- Write concise, technical responses with accurate Python examples
- Use functional, declarative programming; avoid classes where possible
- Prefer iteration and modularization over code duplication
- Use descriptive variable names with auxiliary verbs (e.g., `is_active`, `has_permission`)
- Use lowercase with underscores for directories and files (e.g., `routers/user_routes.py`)
- Favor named exports for routes and utility functions
- Follow the Receive an Object, Return an Object (RORO) pattern
2. **Python/FastAPI Conventions**
- Use `def` for pure functions and `async def` for asynchronous operations
- Use type hints for ALL function signatures
- Prefer Pydantic models over raw dictionaries for input validation
- Standard file structure: exported router, sub-routes, utilities, static content, types (models, schemas)
- Avoid unnecessary curly braces in conditional statements
- Use concise, one-line syntax for simple conditionals: `if condition: do_something()`
3. **Error Handling and Validation**
- Handle errors and edge cases at the beginning of functions
- Use early returns for error conditions to avoid deeply nested if statements
- Place the happy path last in the function for improved readability
- Avoid unnecessary else statements; use the if-return pattern instead
- Use guard clauses to handle preconditions and invalid states early
- Implement proper error logging and user-friendly error messages
- Use custom error types or error factories for consistent error handling
- Use `HTTPException` for expected errors with specific HTTP responses
- Use middleware for handling unexpected errors, logging, and monitoring
4. **FastAPI-Specific Guidelines**
- Use functional components (plain functions) and Pydantic models for validation
- Use declarative route definitions with clear return type annotations
- Minimize `@app.on_event()` decorators; prefer lifespan context managers
- Use middleware for logging, error monitoring, and performance optimization
- Rely on FastAPI's dependency injection system for managing state and shared resources
- Use Pydantic's `BaseModel` for consistent input/output validation and response schemas
5. **Performance Optimization**
- Minimize blocking I/O operations; use async operations for all database calls and external API requests
- Implement caching for static and frequently accessed data (Redis, in-memory stores)
- Optimize data serialization/deserialization with Pydantic
- Use lazy loading techniques for large datasets and substantial API responses
- Favor asynchronous and non-blocking flows throughout
- Structure routes and dependencies clearly to optimize readability and maintainability
6. **Recommended Dependencies**
- FastAPI (core framework)
- Pydantic v2 (validation and serialization)
- Async database libraries: `asyncpg` or `aiomysql`
- SQLAlchemy 2.0 (if using ORM features)
**Route with proper error handling:**
```python
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
router = APIRouter()
class UserResponse(BaseModel):
id: int
username: str
is_active: bool
@router.get("/users/{user_id}", response_model=UserResponse)
async def get_user(user_id: int) -> UserResponse:
# Guard clause - handle errors early
if user_id < 1:
raise HTTPException(status_code=400, detail="Invalid user ID")
user = await fetch_user_from_db(user_id)
# Early return for error case
if not user:
raise HTTPException(status_code=404, detail="User not found")
# Happy path last
return UserResponse(**user)
```
**Lifespan context manager:**
```python
from contextlib import asynccontextmanager
from fastapi import FastAPI
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup
await initialize_database()
yield
# Shutdown
await close_database()
app = FastAPI(lifespan=lifespan)
```
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/fastapi-expert-o1czr4/raw