// FastAPI Expert Development Guidelines
// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})

// What you can build with this ruleset:
A production-ready FastAPI application with:
- Scalable and maintainable API architecture
- Efficient async/await patterns
- Type-safe request/response handling
- Robust error management
- Performance-optimized endpoints
- Clean, functional programming style

// Project Structure
src/
  routers/           # Route handlers by domain
    user_routes.py   # User routes
    auth_routes.py   # Authentication routes
  models/            # Pydantic models and schemas
    domain/          # Domain models
    schemas/         # Request/Response schemas
  services/          # Business logic
  utils/             # Shared utilities
  middleware/        # Custom middleware
  config/            # Configuration management
  tests/             # Test suites

// Development Guidelines
1. Code Quality:
   - Use functional, declarative programming over OOP
   - Implement type hints for all function signatures
   - Follow PEP 8 style guidelines
   - Use descriptive variable names with auxiliary verbs
   - Keep functions focused and small
   - Prefer composition over inheritance

2. API Design:
   - Use Pydantic models for request/response validation
   - Implement clear endpoint naming conventions
   - Structure routes logically by domain
   - Use appropriate HTTP methods and status codes
   - Version APIs explicitly when needed
   - Document all endpoints with OpenAPI specs

3. Error Handling:
   - Handle errors at function entry points
   - Use early returns to avoid nested conditionals
   - Implement custom error types for domain-specific errors
   - Provide clear, actionable error messages
   - Log errors with appropriate context
   - Use HTTPException for API errors

4. Performance:
   - Use async operations for I/O-bound tasks
   - Implement caching strategies
   - Optimize database queries
   - Use connection pooling
   - Implement proper indexing
   - Monitor and optimize response times

// Dependencies
Core:
- FastAPI
- Pydantic v2
- SQLAlchemy 2.0
- asyncpg/aiomysql
- uvicorn
- python-jose[cryptography]
- passlib[bcrypt]

Optional:
- Redis (caching)
- Celery (background tasks)
- Prometheus (metrics)
- Sentry (error tracking)

// Code Examples:

1. Route Definition Pattern:
```python
from fastapi import APIRouter, Depends, HTTPException
from typing import List
from pydantic import BaseModel

router = APIRouter(prefix="/users", tags=["users"])

class UserResponse(BaseModel):
    id: int
    username: str
    email: str

@router.get("/{user_id}", response_model=UserResponse)
async def get_user(user_id: int, db: Database = Depends(get_db)):
    if not (user := await db.users.get(user_id)):
        raise HTTPException(status_code=404, detail="User not found")
    return user
```

2. Error Handling Pattern:
```python
from fastapi import HTTPException
from typing import Optional

async def get_user_or_404(user_id: int, db: Database) -> User:
    # Early return pattern
    if not user_id:
        raise HTTPException(status_code=400, detail="User ID is required")
    
    if not (user := await db.users.get(user_id)):
        raise HTTPException(status_code=404, detail="User not found")
    
    return user
```

3. Dependency Injection Pattern:
```python
from fastapi import Depends
from typing import AsyncGenerator

async def get_db() -> AsyncGenerator[Database, None]:
    async with Database() as db:
        yield db

async def get_current_user(
    token: str = Depends(oauth2_scheme),
    db: Database = Depends(get_db)
) -> User:
    return await validate_token_and_get_user(token, db)
```

// Best Practices:
1. Use dependency injection for shared resources
2. Implement proper connection pooling
3. Use async context managers for resource cleanup
4. Implement proper request validation
5. Use appropriate status codes
6. Implement proper logging
7. Use proper error handling
8. Implement proper caching
9. Use proper security measures
10. Implement proper testing

// Security Considerations:
1. Implement proper authentication
2. Use proper authorization
3. Implement rate limiting
4. Use CORS properly
5. Implement proper input validation
6. Use secure headers
7. Implement proper logging
8. Use proper error handling
9. Implement proper security headers
10. Use proper SSL/TLS
