File size: 6,566 Bytes
194469b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 | # 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
|