|
Download docs/dev/fastapi-rules.md from Atomio/facerecog: direct link, hf CLI and curl.
- Browser
- Download file 6.57 kB
-
https://huggingface.co/spaces/Atomio/facerecog/resolve/main/docs/dev/fastapi-rules.md
- Command line
-
hf download hf://spaces/Atomio/facerecog/docs/dev/fastapi-rules.md
-
curl -L -o fastapi-rules.md https://huggingface.co/spaces/Atomio/facerecog/resolve/main/docs/dev/fastapi-rules.md
6.57 kB
| # 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 | |