facerecog / docs /dev /fastapi-rules.md
atomio
Initial commit
194469b
|
Raw History Blame Contribute Delete
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