# FastAPI Development Rules & Best Practices ## ๐Ÿ—๏ธ Project Structure Rules ### 1. Domain-Driven Structure - Organize code by business domains, not by file types - Each domain should be self-contained with its own models, schemas, services, etc. - Use explicit imports with module names to avoid conflicts ### 2. File Organization ``` src/ โ”œโ”€โ”€ domain_name/ โ”‚ โ”œโ”€โ”€ router.py # API endpoints โ”‚ โ”œโ”€โ”€ schemas.py # Pydantic models โ”‚ โ”œโ”€โ”€ models.py # Database models โ”‚ โ”œโ”€โ”€ service.py # Business logic โ”‚ โ”œโ”€โ”€ dependencies.py # Route dependencies โ”‚ โ”œโ”€โ”€ exceptions.py # Domain-specific exceptions โ”‚ โ”œโ”€โ”€ constants.py # Domain constants โ”‚ โ”œโ”€โ”€ config.py # Domain configuration โ”‚ โ””โ”€โ”€ utils.py # Utility functions โ”œโ”€โ”€ config.py # Global configuration โ”œโ”€โ”€ database.py # Database connection โ”œโ”€โ”€ exceptions.py # Global exceptions โ””โ”€โ”€ main.py # FastAPI app initialization ``` ## ๐Ÿ”„ Async/Await Rules ### 1. Always Use Async for I/O Operations - **DO**: Use `async def` for routes that perform I/O (database, external APIs, file operations) - **DON'T**: Use `time.sleep()` in async functions - use `asyncio.sleep()` instead - **DON'T**: Mix sync and async operations without proper handling ### 2. Thread Pool for Sync Libraries - If you must use sync libraries, wrap them with `run_in_threadpool` - Example: `await run_in_threadpool(sync_function, arg1, arg2)` ### 3. Prefer Async Dependencies - Use `async def` for dependencies unless you have a specific reason not to - Dependencies are cached within request scope ## ๐Ÿ“ Pydantic Rules ### 1. Use Custom Base Model - Create a global `CustomModel` base class for consistent behavior - Include common configurations and methods ### 2. Validation Rules - Use Pydantic validators for complex validation logic - Raise `ValueError` for validation errors (automatically converted to HTTP 422) - Use `Field()` for additional constraints and documentation ### 3. Response Models - Always define `response_model` for endpoints - Use separate schemas for request/response when they differ - Don't return Pydantic objects directly - return dicts for better performance ## ๐Ÿ”— Dependencies Rules ### 1. Use Dependencies for Validation - Validate database constraints in dependencies, not in route handlers - Chain dependencies to avoid code duplication - Use dependencies for authentication, authorization, and data validation ### 2. Dependency Naming - Use descriptive names: `valid_user_id`, `authenticated_user`, `active_subscription` - Return meaningful data structures from dependencies ### 3. Error Handling in Dependencies - Raise specific HTTP exceptions in dependencies - Use custom exception classes for domain-specific errors ## ๐Ÿ›ก๏ธ Error Handling Rules ### 1. Custom Exceptions - Create domain-specific exception classes - Inherit from `HTTPException` or create custom exception handlers - Use consistent error response format ### 2. Global Exception Handlers - Register global exception handlers for common errors - Log errors appropriately (don't log validation errors as errors) ## ๐Ÿ—„๏ธ Database Rules ### 1. Async Database Operations - Use async database drivers (asyncpg for PostgreSQL) - Use connection pooling - Handle database errors gracefully ### 2. Query Optimization - Prefer SQL aggregations over Python processing - Use database indexes appropriately - Avoid N+1 query problems ### 3. Migrations - Use descriptive migration names with dates - Make migrations reversible - Test migrations on staging before production ## ๐Ÿ”’ Security Rules ### 1. Input Validation - Validate all inputs using Pydantic - Sanitize file uploads - Use parameterized queries (SQLAlchemy handles this) ### 2. Authentication & Authorization - Use dependency injection for auth checks - Implement proper JWT handling - Use HTTPS in production ### 3. Environment Variables - Never commit secrets to version control - Use `.env` files for local development - Validate environment variables on startup ## ๐Ÿ“š Documentation Rules ### 1. API Documentation - Use descriptive endpoint names and descriptions - Document all possible response codes - Include examples in docstrings ### 2. Code Documentation - Write docstrings for all public functions and classes - Use type hints consistently - Comment complex business logic ## ๐Ÿงช Testing Rules ### 1. Test Structure - Mirror source structure in tests - Use async test client from day one - Separate unit tests from integration tests ### 2. Test Coverage - Aim for high test coverage on business logic - Test error conditions and edge cases - Use factories for test data generation ## ๐Ÿš€ Performance Rules ### 1. Response Optimization - Use appropriate HTTP status codes - Implement pagination for list endpoints - Use compression for large responses ### 2. Caching - Cache expensive computations - Use Redis for session storage and caching - Implement proper cache invalidation ## ๐Ÿ“ฆ Deployment Rules ### 1. Configuration Management - Use environment-specific configurations - Validate configuration on startup - Use secrets management for sensitive data ### 2. Monitoring & Logging - Implement structured logging - Use correlation IDs for request tracing - Monitor application metrics ## ๐Ÿ”ง Development Tools ### 1. Code Quality - Use `ruff` for linting and formatting - Use `mypy` for type checking - Use pre-commit hooks ### 2. Development Environment - Use virtual environments - Pin dependency versions - Use Docker for consistent environments ## โŒ Common Anti-Patterns to Avoid 1. **Don't** put business logic in route handlers 2. **Don't** use global variables for request-specific data 3. **Don't** ignore error handling 4. **Don't** mix sync and async code incorrectly 5. **Don't** return Pydantic models directly from endpoints 6. **Don't** use `sync` dependencies when `async` would work 7. **Don't** put database queries in route handlers 8. **Don't** ignore security best practices 9. **Don't** skip input validation 10. **Don't** commit secrets or sensitive data ## โœ… Code Review Checklist - [ ] Follows project structure conventions - [ ] Uses async/await correctly - [ ] Includes proper error handling - [ ] Has appropriate tests - [ ] Includes type hints - [ ] Follows naming conventions - [ ] Includes documentation - [ ] Handles edge cases - [ ] Follows security best practices - [ ] Uses dependencies appropriately