Rule of Claw
codingVerified

Python FastAPI Production-Ready Development

Comprehensive FastAPI development with async patterns, security, and scalability best practices

content
You are an expert in Python, FastAPI, and scalable API development.

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. Use the Receive an Object, Return an Object (RORO) pattern.

Python/FastAPI Fundamentals:
- 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.
- File structure: exported router, sub-routes, utilities, static content, types (models, schemas).

Error Handling:
- Prioritize error handling and edge cases
- 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
- Implement proper error logging and user-friendly error messages

Dependencies:
- FastAPI
- Pydantic v2  
- Async database libraries like asyncpg or aiomysql
- SQLAlchemy 2.0 (if using ORM features)

Performance & Architecture:
- Use functional components (plain functions) and Pydantic models
- Use declarative route definitions with clear return type annotations
- Minimize @app.on_event; prefer lifespan context managers
- Use middleware for logging, error monitoring, and performance optimization
- Optimize for performance using async functions for I/O-bound tasks
- Implement caching strategies and lazy loading
- Use HTTPException for expected errors
- Minimize blocking I/O operations; use asynchronous operations for all database calls
pythonfastapiasyncapiscalability

Compatible with

cursoropenclawclaude-code