<turbo-stream action="update" target="modal_container"><template>
  <div data-controller="agent-modal"
     data-agent-modal-current-tab-value="overview"
     class="hidden fixed inset-0 z-50">

  <!-- Backdrop -->
  <div data-action="click->agent-modal#close"
       data-agent-modal-target="backdrop"
       class="fixed inset-0 bg-black/70 transition-opacity duration-200 opacity-0 backdrop-blur-sm"></div>

  <!-- Modal -->
  <div class="fixed inset-0 overflow-y-auto">
    <div class="flex min-h-full items-center justify-center p-4 sm:p-6">
      <div data-agent-modal-target="modal"
           class="modal-content relative w-full max-w-[90vw] transform transition-all duration-200 opacity-0 scale-95">

        <div class="relative bg-white dark:bg-gray-800 rounded-xl shadow-2xl border border-gray-200 dark:border-gray-700 h-[90vh] flex flex-col">

          <!-- Header with Tabs -->
          <div class="flex-shrink-0 border-b border-gray-200 dark:border-gray-700">
            <!-- Title and Close -->
            <div class="flex items-center justify-between px-6 py-4">
              <div>
                <h2 class="text-2xl font-bold text-gray-900 dark:text-white">Api Scaffold Generator</h2>
                <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                  by <a class="hover:text-amber-600 dark:hover:text-amber-400 transition-colors" data-turbo-frame="_top" href="/authors/0199c65d-fb71-77fb-a296-59ef21fceae1">wshobson/agents</a>
                </p>
              </div>
              <button type="button"
                      data-action="click->agent-modal#close"
                      class="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>

            <!-- Action Buttons -->
            <div class="px-6 pb-4 flex flex-wrap items-center gap-3">

              <a data-turbo-frame="_top" class="inline-flex items-center gap-2 px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors" href="/agents/api-scaffold-generator">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                </svg>
                View Full Page
</a>            </div>

            <!-- Tabs -->
            <div class="px-6">
              <nav class="flex gap-1 overflow-x-auto" aria-label="Tabs">
                <button type="button"
                        data-action="click->agent-modal#switchTab"
                        data-tab="overview"
                        data-agent-modal-target="tab"
                        class="px-4 py-2 text-sm font-medium rounded-t-lg whitespace-nowrap transition-colors border-b-2 border-transparent text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 hover:border-gray-300 dark:hover:border-gray-600 [&[data-active]]:text-amber-600 [&[data-active]]:dark:text-amber-400 [&[data-active]]:border-amber-600 [&[data-active]]:dark:border-amber-400 outline-none focus:outline-none active:outline-none">
                  Overview
                </button>

                  <button type="button"
                          data-action="click->agent-modal#switchTab"
                          data-tab="0199c676-5d1c-779d-b714-8d71b700739c"
                          data-agent-modal-target="tab"
                          class="px-4 py-2 text-sm font-medium rounded-t-lg whitespace-nowrap transition-colors border-b-2 border-transparent text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 hover:border-gray-300 dark:hover:border-gray-600 [&[data-active]]:text-amber-600 [&[data-active]]:dark:text-amber-400 [&[data-active]]:border-amber-600 [&[data-active]]:dark:border-amber-400 outline-none focus:outline-none active:outline-none">
                    <div class="flex items-center gap-2"><img alt="Claude" class="w-4 h-4" loading="lazy" src="/assets/claude-7b230d75.svg" /><span class="">Claude</span></div>
                  </button>
              </nav>
            </div>
          </div>

          <!-- Tab Content -->
          <div class="flex-1 overflow-hidden">
            <!-- Overview Tab -->
            <div data-agent-modal-target="tabContent"
                 data-tab="overview"
                 class="hidden h-full overflow-y-auto p-6">
              <div class="space-y-6">
  <div>
    <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-2">Description</h3>
    <div class="text-gray-600 dark:text-gray-400 leading-relaxed">
      <div class="lexxy-content">
  Expert API development assistant that generates production-ready API implementations with comprehensive architecture and best practices
</div>

    </div>
  </div>

  <div>
    <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-2">Available Platforms</h3>
    <div class="flex flex-wrap gap-2">
        <span class="inline-flex items-center gap-1.5 px-3 py-1 text-sm bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 rounded-md">
            <img class="w-4 h-4" alt="Claude" src="/assets/claude-7b230d75.svg" />
          claude
        </span>
    </div>
  </div>

</div>

            </div>

            <!-- Platform Implementation Tabs -->
              <div data-agent-modal-target="tabContent"
                   data-tab="0199c676-5d1c-779d-b714-8d71b700739c"
                   class="hidden h-full">
                <div class="h-full flex flex-col lg:flex-row">
                  <!-- Sidebar (30%) -->
                  <div class="lg:w-[30%] border-b lg:border-b-0 lg:border-r border-gray-200 dark:border-gray-700 p-6 lg:overflow-y-auto">
                    <div class="flex items-center justify-between mb-4">
                      <div class="flex items-center gap-2"><img alt="Claude" class="w-8 h-8" loading="lazy" src="/assets/claude-7b230d75.svg" /><span class="text-xl font-semibold">Claude</span></div>

                      <!-- Quick Actions -->
                      <div class="flex items-center gap-1">
                        
  <button data-controller="download"
          data-download-url-value="/implementations/0199c676-5d1c-779d-b714-8d71b700739c/download"
          data-download-implementation-id-value="0199c676-5d1c-779d-b714-8d71b700739c"
          data-download-agent-id-value="0199c676-5ce2-7334-80c3-79d3c9340fcc"
          data-action="click->download#handleClick"
          class="p-2 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors group"
          title="Download">
    <svg class="w-5 h-5 text-gray-400 dark:text-gray-500 group-hover:text-gray-600 dark:group-hover:text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
    </svg>
  </button>


                      </div>
                    </div>

                    <div class="flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400 mb-6">
                      <span>Version 1.0.1</span>
                        <span class="text-gray-300 dark:text-gray-700">•</span>
                        <span class="inline-flex items-center gap-1" title="MIT License">
                          <img class="w-3 h-3 text-gray-600 dark:text-gray-400" alt="MIT" src="/assets/mit_license-736a4952.svg" />
                          <span class="text-xs">MIT</span>
                        </span>
                    </div>


                    <!-- Copy Button -->
                    <button type="button"
                            data-action="click->agent-modal#copyCode"
                            data-implementation-id="0199c676-5d1c-779d-b714-8d71b700739c"
                            class="w-full inline-flex items-center justify-center gap-2 px-4 py-2 bg-gray-900 dark:bg-gray-700 text-white rounded-lg hover:bg-gray-800 dark:hover:bg-gray-600 transition-colors [&[data-copied]]:!bg-green-600 [&[data-copied]]:dark:!bg-green-500 mb-3">
                      <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" />
                      </svg>
                      <span>Copy to Clipboard</span>
                    </button>

                    <!-- Download Button -->
                    
  <button data-controller="download"
          data-download-url-value="/implementations/0199c676-5d1c-779d-b714-8d71b700739c/download"
          data-download-implementation-id-value="0199c676-5d1c-779d-b714-8d71b700739c"
          data-download-agent-id-value="0199c676-5ce2-7334-80c3-79d3c9340fcc"
          data-action="click->download#handleClick"
          class="w-full px-4 py-2 bg-amber-600 text-white text-sm rounded-md hover:bg-amber-700 transition-colors text-center font-medium">
    Download
  </button>

                  </div>

                  <!-- Code Content (70%) -->
                  <div class="flex-1 lg:w-[70%] overflow-y-auto p-6 bg-gray-50 dark:bg-gray-900/50">
                    <pre class="text-sm leading-relaxed text-gray-900 dark:text-gray-100 whitespace-pre-wrap font-mono" data-code-content="0199c676-5d1c-779d-b714-8d71b700739c">---
model: claude-sonnet-4-0
---

# API Scaffold Generator

You are an API development expert specializing in creating production-ready, scalable REST APIs with modern frameworks. Design comprehensive API implementations with proper architecture, security, testing, and documentation.

## Context
The user needs to create a new API endpoint or service with complete implementation including models, validation, security, testing, and deployment configuration. Focus on production-ready code that follows industry best practices.

## Requirements
$ARGUMENTS

## Instructions

### 1. API Framework Selection

Choose the appropriate framework based on requirements:

**Framework Comparison Matrix**
```python
def select_framework(requirements):
    &quot;&quot;&quot;Select optimal API framework based on requirements&quot;&quot;&quot;
    
    frameworks = {
        &#39;fastapi&#39;: {
            &#39;best_for&#39;: [&#39;high_performance&#39;, &#39;async_operations&#39;, &#39;type_safety&#39;, &#39;modern_python&#39;],
            &#39;strengths&#39;: [&#39;Auto OpenAPI docs&#39;, &#39;Type hints&#39;, &#39;Async support&#39;, &#39;Fast performance&#39;],
            &#39;use_cases&#39;: [&#39;Microservices&#39;, &#39;Data APIs&#39;, &#39;ML APIs&#39;, &#39;Real-time systems&#39;],
            &#39;example_stack&#39;: &#39;FastAPI + Pydantic + SQLAlchemy + PostgreSQL&#39;
        },
        &#39;django_rest&#39;: {
            &#39;best_for&#39;: [&#39;rapid_development&#39;, &#39;orm_integration&#39;, &#39;admin_interface&#39;, &#39;large_teams&#39;],
            &#39;strengths&#39;: [&#39;Batteries included&#39;, &#39;ORM&#39;, &#39;Admin panel&#39;, &#39;Mature ecosystem&#39;],
            &#39;use_cases&#39;: [&#39;CRUD applications&#39;, &#39;Content management&#39;, &#39;Enterprise systems&#39;],
            &#39;example_stack&#39;: &#39;Django + DRF + PostgreSQL + Redis&#39;
        },
        &#39;express&#39;: {
            &#39;best_for&#39;: [&#39;node_ecosystem&#39;, &#39;real_time&#39;, &#39;frontend_integration&#39;, &#39;javascript_teams&#39;],
            &#39;strengths&#39;: [&#39;NPM ecosystem&#39;, &#39;JSON handling&#39;, &#39;WebSocket support&#39;, &#39;Fast development&#39;],
            &#39;use_cases&#39;: [&#39;Real-time apps&#39;, &#39;API gateways&#39;, &#39;Serverless functions&#39;],
            &#39;example_stack&#39;: &#39;Express + TypeScript + Prisma + PostgreSQL&#39;
        },
        &#39;spring_boot&#39;: {
            &#39;best_for&#39;: [&#39;enterprise&#39;, &#39;java_teams&#39;, &#39;complex_business_logic&#39;, &#39;microservices&#39;],
            &#39;strengths&#39;: [&#39;Enterprise features&#39;, &#39;Dependency injection&#39;, &#39;Security&#39;, &#39;Monitoring&#39;],
            &#39;use_cases&#39;: [&#39;Enterprise APIs&#39;, &#39;Financial systems&#39;, &#39;Complex microservices&#39;],
            &#39;example_stack&#39;: &#39;Spring Boot + JPA + PostgreSQL + Redis&#39;
        }
    }
    
    # Selection logic based on requirements
    if &#39;high_performance&#39; in requirements:
        return frameworks[&#39;fastapi&#39;]
    elif &#39;enterprise&#39; in requirements:
        return frameworks[&#39;spring_boot&#39;]
    elif &#39;rapid_development&#39; in requirements:
        return frameworks[&#39;django_rest&#39;]
    elif &#39;real_time&#39; in requirements:
        return frameworks[&#39;express&#39;]
    
    return frameworks[&#39;fastapi&#39;]  # Default recommendation
```

### 2. FastAPI Implementation

Complete FastAPI API implementation:

**Project Structure**
```
project/
âââ app/
â   âââ __init__.py
â   âââ main.py
â   âââ core/
â   â   âââ config.py
â   â   âââ security.py
â   â   âââ database.py
â   âââ api/
â   â   âââ __init__.py
â   â   âââ deps.py
â   â   âââ v1/
â   â       âââ __init__.py
â   â       âââ endpoints/
â   â       â   âââ users.py
â   â       â   âââ items.py
â   â       âââ api.py
â   âââ models/
â   â   âââ __init__.py
â   â   âââ user.py
â   â   âââ item.py
â   âââ schemas/
â   â   âââ __init__.py
â   â   âââ user.py
â   â   âââ item.py
â   âââ services/
â   â   âââ __init__.py
â   â   âââ user_service.py
â   â   âââ item_service.py
â   âââ tests/
â       âââ conftest.py
â       âââ test_users.py
â       âââ test_items.py
âââ alembic/
âââ requirements.txt
âââ Dockerfile
âââ docker-compose.yml
```

**Core Configuration**
```python
# app/core/config.py
from pydantic import BaseSettings, validator
from typing import Optional, Dict, Any
import secrets

class Settings(BaseSettings):
    API_V1_STR: str = &quot;/api/v1&quot;
    SECRET_KEY: str = secrets.token_urlsafe(32)
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8  # 8 days
    SERVER_NAME: str = &quot;localhost&quot;
    SERVER_HOST: str = &quot;0.0.0.0&quot;
    
    # Database
    POSTGRES_SERVER: str = &quot;localhost&quot;
    POSTGRES_USER: str = &quot;postgres&quot;
    POSTGRES_PASSWORD: str = &quot;&quot;
    POSTGRES_DB: str = &quot;app&quot;
    DATABASE_URL: Optional[str] = None
    
    @validator(&quot;DATABASE_URL&quot;, pre=True)
    def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -&gt; Any:
        if isinstance(v, str):
            return v
        return f&quot;postgresql://{values.get(&#39;POSTGRES_USER&#39;)}:{values.get(&#39;POSTGRES_PASSWORD&#39;)}@{values.get(&#39;POSTGRES_SERVER&#39;)}/{values.get(&#39;POSTGRES_DB&#39;)}&quot;
    
    # Redis
    REDIS_URL: str = &quot;redis://localhost:6379&quot;
    
    # Security
    BACKEND_CORS_ORIGINS: list = [&quot;http://localhost:3000&quot;, &quot;http://localhost:8000&quot;]
    
    # Rate Limiting
    RATE_LIMIT_REQUESTS: int = 100
    RATE_LIMIT_WINDOW: int = 60
    
    # Monitoring
    SENTRY_DSN: Optional[str] = None
    LOG_LEVEL: str = &quot;INFO&quot;
    
    class Config:
        env_file = &quot;.env&quot;

settings = Settings()
```

**Database Setup**
```python
# app/core/database.py
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
import redis

from app.core.config import settings

# PostgreSQL
engine = create_engine(
    settings.DATABASE_URL,
    poolclass=StaticPool,
    pool_size=20,
    max_overflow=30,
    pool_pre_ping=True,
    echo=settings.LOG_LEVEL == &quot;DEBUG&quot;
)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

# Redis
redis_client = redis.from_url(settings.REDIS_URL, decode_responses=True)

def get_db():
    &quot;&quot;&quot;Dependency to get database session&quot;&quot;&quot;
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

def get_redis():
    &quot;&quot;&quot;Dependency to get Redis connection&quot;&quot;&quot;
    return redis_client
```

**Security Implementation**
```python
# app/core/security.py
from datetime import datetime, timedelta
from typing import Optional
import jwt
from passlib.context import CryptContext
from fastapi import HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

from app.core.config import settings

pwd_context = CryptContext(schemes=[&quot;bcrypt&quot;], deprecated=&quot;auto&quot;)
security = HTTPBearer()

def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
    &quot;&quot;&quot;Create JWT access token&quot;&quot;&quot;
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    
    to_encode.update({&quot;exp&quot;: expire})
    encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=&quot;HS256&quot;)
    return encoded_jwt

def verify_token(credentials: HTTPAuthorizationCredentials) -&gt; dict:
    &quot;&quot;&quot;Verify JWT token&quot;&quot;&quot;
    try:
        payload = jwt.decode(
            credentials.credentials, 
            settings.SECRET_KEY, 
            algorithms=[&quot;HS256&quot;]
        )
        username: str = payload.get(&quot;sub&quot;)
        if username is None:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail=&quot;Could not validate credentials&quot;,
                headers={&quot;WWW-Authenticate&quot;: &quot;Bearer&quot;},
            )
        return payload
    except jwt.PyJWTError:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=&quot;Could not validate credentials&quot;,
            headers={&quot;WWW-Authenticate&quot;: &quot;Bearer&quot;},
        )

def verify_password(plain_password: str, hashed_password: str) -&gt; bool:
    &quot;&quot;&quot;Verify password against hash&quot;&quot;&quot;
    return pwd_context.verify(plain_password, hashed_password)

def get_password_hash(password: str) -&gt; str:
    &quot;&quot;&quot;Generate password hash&quot;&quot;&quot;
    return pwd_context.hash(password)
```

**Models Implementation**
```python
# app/models/user.py
from sqlalchemy import Column, Integer, String, Boolean, DateTime, Text
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship

from app.core.database import Base

class User(Base):
    __tablename__ = &quot;users&quot;
    
    id = Column(Integer, primary_key=True, index=True)
    email = Column(String, unique=True, index=True, nullable=False)
    username = Column(String, unique=True, index=True, nullable=False)
    hashed_password = Column(String, nullable=False)
    full_name = Column(String)
    is_active = Column(Boolean, default=True)
    is_superuser = Column(Boolean, default=False)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # Relationships
    items = relationship(&quot;Item&quot;, back_populates=&quot;owner&quot;)

# app/models/item.py
from sqlalchemy import Column, Integer, String, Boolean, DateTime, Text, ForeignKey
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship

from app.core.database import Base

class Item(Base):
    __tablename__ = &quot;items&quot;
    
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, index=True, nullable=False)
    description = Column(Text)
    is_active = Column(Boolean, default=True)
    owner_id = Column(Integer, ForeignKey(&quot;users.id&quot;))
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # Relationships
    owner = relationship(&quot;User&quot;, back_populates=&quot;items&quot;)
```

**Pydantic Schemas**
```python
# app/schemas/user.py
from pydantic import BaseModel, EmailStr, validator
from typing import Optional
from datetime import datetime

class UserBase(BaseModel):
    email: EmailStr
    username: str
    full_name: Optional[str] = None

class UserCreate(UserBase):
    password: str
    
    @validator(&#39;password&#39;)
    def validate_password(cls, v):
        if len(v) &lt; 8:
            raise ValueError(&#39;Password must be at least 8 characters&#39;)
        return v

class UserUpdate(BaseModel):
    email: Optional[EmailStr] = None
    username: Optional[str] = None
    full_name: Optional[str] = None
    is_active: Optional[bool] = None

class UserInDB(UserBase):
    id: int
    is_active: bool
    is_superuser: bool
    created_at: datetime
    updated_at: Optional[datetime]
    
    class Config:
        orm_mode = True

class User(UserInDB):
    pass

# app/schemas/item.py
from pydantic import BaseModel, validator
from typing import Optional
from datetime import datetime

class ItemBase(BaseModel):
    title: str
    description: Optional[str] = None

class ItemCreate(ItemBase):
    @validator(&#39;title&#39;)
    def validate_title(cls, v):
        if len(v.strip()) &lt; 3:
            raise ValueError(&#39;Title must be at least 3 characters&#39;)
        return v.strip()

class ItemUpdate(BaseModel):
    title: Optional[str] = None
    description: Optional[str] = None
    is_active: Optional[bool] = None

class ItemInDB(ItemBase):
    id: int
    is_active: bool
    owner_id: int
    created_at: datetime
    updated_at: Optional[datetime]
    
    class Config:
        orm_mode = True

class Item(ItemInDB):
    pass
```

**Service Layer**
```python
# app/services/user_service.py
from typing import Optional, List
from sqlalchemy.orm import Session
from fastapi import HTTPException, status

from app.models.user import User
from app.schemas.user import UserCreate, UserUpdate
from app.core.security import get_password_hash, verify_password

class UserService:
    def __init__(self, db: Session):
        self.db = db
    
    def get_user(self, user_id: int) -&gt; Optional[User]:
        &quot;&quot;&quot;Get user by ID&quot;&quot;&quot;
        return self.db.query(User).filter(User.id == user_id).first()
    
    def get_user_by_email(self, email: str) -&gt; Optional[User]:
        &quot;&quot;&quot;Get user by email&quot;&quot;&quot;
        return self.db.query(User).filter(User.email == email).first()
    
    def get_users(self, skip: int = 0, limit: int = 100) -&gt; List[User]:
        &quot;&quot;&quot;Get list of users&quot;&quot;&quot;
        return self.db.query(User).offset(skip).limit(limit).all()
    
    def create_user(self, user_create: UserCreate) -&gt; User:
        &quot;&quot;&quot;Create new user&quot;&quot;&quot;
        # Check if user exists
        if self.get_user_by_email(user_create.email):
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=&quot;Email already registered&quot;
            )
        
        # Create user
        hashed_password = get_password_hash(user_create.password)
        db_user = User(
            email=user_create.email,
            username=user_create.username,
            full_name=user_create.full_name,
            hashed_password=hashed_password
        )
        self.db.add(db_user)
        self.db.commit()
        self.db.refresh(db_user)
        return db_user
    
    def update_user(self, user_id: int, user_update: UserUpdate) -&gt; User:
        &quot;&quot;&quot;Update user&quot;&quot;&quot;
        db_user = self.get_user(user_id)
        if not db_user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=&quot;User not found&quot;
            )
        
        update_data = user_update.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(db_user, field, value)
        
        self.db.commit()
        self.db.refresh(db_user)
        return db_user
    
    def authenticate_user(self, email: str, password: str) -&gt; Optional[User]:
        &quot;&quot;&quot;Authenticate user&quot;&quot;&quot;
        user = self.get_user_by_email(email)
        if not user or not verify_password(password, user.hashed_password):
            return None
        return user
```

**Rate Limiting Middleware**
```python
# app/core/rate_limiting.py
import time
from typing import Callable
from fastapi import Request, HTTPException, status
from fastapi.responses import JSONResponse
import redis

from app.core.config import settings
from app.core.database import get_redis

class RateLimiter:
    def __init__(self, redis_client: redis.Redis):
        self.redis = redis_client
        self.requests = settings.RATE_LIMIT_REQUESTS
        self.window = settings.RATE_LIMIT_WINDOW
    
    async def __call__(self, request: Request, call_next: Callable):
        # Get client identifier
        client_ip = request.client.host
        user_id = getattr(request.state, &#39;user_id&#39;, None)
        key = f&quot;rate_limit:{user_id or client_ip}&quot;
        
        # Check rate limit
        current = self.redis.get(key)
        if current is None:
            # First request in window
            self.redis.setex(key, self.window, 1)
        else:
            current = int(current)
            if current &gt;= self.requests:
                raise HTTPException(
                    status_code=status.HTTP_429_TOO_MANY_REQUESTS,
                    detail=f&quot;Rate limit exceeded. Try again in {self.redis.ttl(key)} seconds&quot;,
                    headers={&quot;Retry-After&quot;: str(self.redis.ttl(key))}
                )
            self.redis.incr(key)
        
        response = await call_next(request)
        
        # Add rate limit headers
        remaining = max(0, self.requests - int(self.redis.get(key) or 0))
        response.headers[&quot;X-RateLimit-Limit&quot;] = str(self.requests)
        response.headers[&quot;X-RateLimit-Remaining&quot;] = str(remaining)
        response.headers[&quot;X-RateLimit-Reset&quot;] = str(int(time.time()) + self.redis.ttl(key))
        
        return response
```

**API Endpoints**
```python
# app/api/v1/endpoints/users.py
from typing import List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from app.core.database import get_db
from app.core.security import verify_token, security
from app.schemas.user import User, UserCreate, UserUpdate
from app.services.user_service import UserService

router = APIRouter()

@router.post(&quot;/&quot;, response_model=User, status_code=status.HTTP_201_CREATED)
async def create_user(
    user_create: UserCreate,
    db: Session = Depends(get_db)
):
    &quot;&quot;&quot;Create new user&quot;&quot;&quot;
    service = UserService(db)
    return service.create_user(user_create)

@router.get(&quot;/me&quot;, response_model=User)
async def get_current_user(
    token: dict = Depends(verify_token),
    db: Session = Depends(get_db)
):
    &quot;&quot;&quot;Get current user profile&quot;&quot;&quot;
    service = UserService(db)
    user = service.get_user_by_email(token[&quot;sub&quot;])
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=&quot;User not found&quot;
        )
    return user

@router.get(&quot;/{user_id}&quot;, response_model=User)
async def get_user(
    user_id: int,
    db: Session = Depends(get_db),
    token: dict = Depends(verify_token)
):
    &quot;&quot;&quot;Get user by ID&quot;&quot;&quot;
    service = UserService(db)
    user = service.get_user(user_id)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=&quot;User not found&quot;
        )
    return user

@router.put(&quot;/{user_id}&quot;, response_model=User)
async def update_user(
    user_id: int,
    user_update: UserUpdate,
    db: Session = Depends(get_db),
    token: dict = Depends(verify_token)
):
    &quot;&quot;&quot;Update user&quot;&quot;&quot;
    service = UserService(db)
    return service.update_user(user_id, user_update)

@router.get(&quot;/&quot;, response_model=List[User])
async def list_users(
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db),
    token: dict = Depends(verify_token)
):
    &quot;&quot;&quot;List users&quot;&quot;&quot;
    service = UserService(db)
    return service.get_users(skip=skip, limit=limit)
```

**Main Application**
```python
# app/main.py
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.responses import JSONResponse
import logging
import time
import uuid

from app.core.config import settings
from app.core.rate_limiting import RateLimiter
from app.core.database import get_redis
from app.api.v1.api import api_router

# Configure logging
logging.basicConfig(
    level=getattr(logging, settings.LOG_LEVEL),
    format=&quot;%(asctime)s - %(name)s - %(levelname)s - %(message)s&quot;
)
logger = logging.getLogger(__name__)

# Create FastAPI app
app = FastAPI(
    title=&quot;Production API&quot;,
    description=&quot;A production-ready API with FastAPI&quot;,
    version=&quot;1.0.0&quot;,
    openapi_url=f&quot;{settings.API_V1_STR}/openapi.json&quot;
)

# Middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.BACKEND_CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=[&quot;*&quot;],
    allow_headers=[&quot;*&quot;],
)

app.add_middleware(
    TrustedHostMiddleware,
    allowed_hosts=[&quot;localhost&quot;, &quot;127.0.0.1&quot;, settings.SERVER_NAME]
)

# Rate limiting middleware
rate_limiter = RateLimiter(get_redis())
app.middleware(&quot;http&quot;)(rate_limiter)

@app.middleware(&quot;http&quot;)
async def add_process_time_header(request: Request, call_next):
    &quot;&quot;&quot;Add processing time and correlation ID&quot;&quot;&quot;
    correlation_id = str(uuid.uuid4())
    request.state.correlation_id = correlation_id
    
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    
    response.headers[&quot;X-Process-Time&quot;] = str(process_time)
    response.headers[&quot;X-Correlation-ID&quot;] = correlation_id
    return response

@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    &quot;&quot;&quot;Global exception handler&quot;&quot;&quot;
    correlation_id = getattr(request.state, &#39;correlation_id&#39;, &#39;unknown&#39;)
    
    logger.error(
        f&quot;Unhandled exception: {exc}&quot;,
        extra={&quot;correlation_id&quot;: correlation_id, &quot;path&quot;: request.url.path}
    )
    
    return JSONResponse(
        status_code=500,
        content={
            &quot;detail&quot;: &quot;Internal server error&quot;,
            &quot;correlation_id&quot;: correlation_id
        }
    )

# Include routers
app.include_router(api_router, prefix=settings.API_V1_STR)

@app.get(&quot;/health&quot;)
async def health_check():
    &quot;&quot;&quot;Health check endpoint&quot;&quot;&quot;
    return {&quot;status&quot;: &quot;healthy&quot;, &quot;timestamp&quot;: time.time()}

@app.get(&quot;/&quot;)
async def root():
    &quot;&quot;&quot;Root endpoint&quot;&quot;&quot;
    return {&quot;message&quot;: &quot;Welcome to the Production API&quot;}

if __name__ == &quot;__main__&quot;:
    import uvicorn
    uvicorn.run(
        &quot;app.main:app&quot;,
        host=settings.SERVER_HOST,
        port=8000,
        reload=True
    )
```

### 3. Express.js Implementation

Complete Express.js TypeScript implementation:

**Project Structure &amp; Setup**
```typescript
// package.json
{
  &quot;name&quot;: &quot;express-api&quot;,
  &quot;version&quot;: &quot;1.0.0&quot;,
  &quot;scripts&quot;: {
    &quot;dev&quot;: &quot;nodemon src/index.ts&quot;,
    &quot;build&quot;: &quot;tsc&quot;,
    &quot;start&quot;: &quot;node dist/index.js&quot;,
    &quot;test&quot;: &quot;jest&quot;,
    &quot;test:watch&quot;: &quot;jest --watch&quot;
  },
  &quot;dependencies&quot;: {
    &quot;express&quot;: &quot;^4.18.2&quot;,
    &quot;express-rate-limit&quot;: &quot;^6.10.0&quot;,
    &quot;helmet&quot;: &quot;^7.0.0&quot;,
    &quot;cors&quot;: &quot;^2.8.5&quot;,
    &quot;compression&quot;: &quot;^1.7.4&quot;,
    &quot;morgan&quot;: &quot;^1.10.0&quot;,
    &quot;joi&quot;: &quot;^17.9.2&quot;,
    &quot;jsonwebtoken&quot;: &quot;^9.0.2&quot;,
    &quot;bcryptjs&quot;: &quot;^2.4.3&quot;,
    &quot;prisma&quot;: &quot;^5.1.0&quot;,
    &quot;@prisma/client&quot;: &quot;^5.1.0&quot;,
    &quot;redis&quot;: &quot;^4.6.7&quot;,
    &quot;winston&quot;: &quot;^3.10.0&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@types/express&quot;: &quot;^4.17.17&quot;,
    &quot;@types/node&quot;: &quot;^20.4.5&quot;,
    &quot;typescript&quot;: &quot;^5.1.6&quot;,
    &quot;nodemon&quot;: &quot;^3.0.1&quot;,
    &quot;jest&quot;: &quot;^29.6.1&quot;,
    &quot;@types/jest&quot;: &quot;^29.5.3&quot;,
    &quot;supertest&quot;: &quot;^6.3.3&quot;
  }
}

// src/types/index.ts
export interface User {
  id: string;
  email: string;
  username: string;
  fullName?: string;
  isActive: boolean;
  createdAt: Date;
  updatedAt: Date;
}

export interface CreateUserRequest {
  email: string;
  username: string;
  password: string;
  fullName?: string;
}

export interface AuthTokenPayload {
  userId: string;
  email: string;
  iat: number;
  exp: number;
}

// src/config/index.ts
import { config as dotenvConfig } from &#39;dotenv&#39;;

dotenvConfig();

export const config = {
  port: parseInt(process.env.PORT || &#39;3000&#39;),
  jwtSecret: process.env.JWT_SECRET || &#39;your-secret-key&#39;,
  jwtExpiresIn: process.env.JWT_EXPIRES_IN || &#39;7d&#39;,
  redisUrl: process.env.REDIS_URL || &#39;redis://localhost:6379&#39;,
  databaseUrl: process.env.DATABASE_URL || &#39;postgresql://user:pass@localhost:5432/db&#39;,
  nodeEnv: process.env.NODE_ENV || &#39;development&#39;,
  corsOrigins: process.env.CORS_ORIGINS?.split(&#39;,&#39;) || [&#39;http://localhost:3000&#39;],
  rateLimitMax: parseInt(process.env.RATE_LIMIT_MAX || &#39;100&#39;),
  rateLimitWindow: parseInt(process.env.RATE_LIMIT_WINDOW_MS || &#39;900000&#39;), // 15 minutes
};

// src/middleware/validation.ts
import { Request, Response, NextFunction } from &#39;express&#39;;
import Joi from &#39;joi&#39;;

export const validateRequest = (schema: Joi.ObjectSchema) =&gt; {
  return (req: Request, res: Response, next: NextFunction) =&gt; {
    const { error } = schema.validate(req.body);
    
    if (error) {
      return res.status(400).json({
        success: false,
        message: &#39;Validation error&#39;,
        details: error.details.map(detail =&gt; ({
          field: detail.path.join(&#39;.&#39;),
          message: detail.message
        }))
      });
    }
    
    next();
  };
};

// Validation schemas
export const userSchemas = {
  create: Joi.object({
    email: Joi.string().email().required(),
    username: Joi.string().alphanum().min(3).max(30).required(),
    password: Joi.string().min(8).required(),
    fullName: Joi.string().max(100).optional()
  }),
  
  update: Joi.object({
    email: Joi.string().email().optional(),
    username: Joi.string().alphanum().min(3).max(30).optional(),
    fullName: Joi.string().max(100).optional(),
    isActive: Joi.boolean().optional()
  })
};

// src/middleware/auth.ts
import { Request, Response, NextFunction } from &#39;express&#39;;
import jwt from &#39;jsonwebtoken&#39;;
import { config } from &#39;../config&#39;;
import { AuthTokenPayload } from &#39;../types&#39;;

declare global {
  namespace Express {
    interface Request {
      user?: AuthTokenPayload;
    }
  }
}

export const authenticateToken = (req: Request, res: Response, next: NextFunction) =&gt; {
  const authHeader = req.headers.authorization;
  const token = authHeader &amp;&amp; authHeader.split(&#39; &#39;)[1];

  if (!token) {
    return res.status(401).json({
      success: false,
      message: &#39;Access token required&#39;
    });
  }

  try {
    const decoded = jwt.verify(token, config.jwtSecret) as AuthTokenPayload;
    req.user = decoded;
    next();
  } catch (error) {
    return res.status(403).json({
      success: false,
      message: &#39;Invalid or expired token&#39;
    });
  }
};

// src/services/userService.ts
import { PrismaClient } from &#39;@prisma/client&#39;;
import bcrypt from &#39;bcryptjs&#39;;
import jwt from &#39;jsonwebtoken&#39;;
import { config } from &#39;../config&#39;;
import { CreateUserRequest, User } from &#39;../types&#39;;

const prisma = new PrismaClient();

export class UserService {
  async createUser(userData: CreateUserRequest): Promise&lt;User&gt; {
    // Check if user exists
    const existingUser = await prisma.user.findFirst({
      where: {
        OR: [
          { email: userData.email },
          { username: userData.username }
        ]
      }
    });

    if (existingUser) {
      throw new Error(&#39;User with this email or username already exists&#39;);
    }

    // Hash password
    const hashedPassword = await bcrypt.hash(userData.password, 12);

    // Create user
    const user = await prisma.user.create({
      data: {
        email: userData.email,
        username: userData.username,
        fullName: userData.fullName,
        hashedPassword,
        isActive: true
      }
    });

    // Remove password from response
    const { hashedPassword: _, ...userWithoutPassword } = user;
    return userWithoutPassword as User;
  }

  async getUserById(id: string): Promise&lt;User | null&gt; {
    const user = await prisma.user.findUnique({
      where: { id },
      select: {
        id: true,
        email: true,
        username: true,
        fullName: true,
        isActive: true,
        createdAt: true,
        updatedAt: true
      }
    });

    return user;
  }

  async authenticateUser(email: string, password: string): Promise&lt;string | null&gt; {
    const user = await prisma.user.findUnique({
      where: { email }
    });

    if (!user || !await bcrypt.compare(password, user.hashedPassword)) {
      return null;
    }

    const token = jwt.sign(
      { userId: user.id, email: user.email },
      config.jwtSecret,
      { expiresIn: config.jwtExpiresIn }
    );

    return token;
  }

  async getUsers(skip = 0, take = 10): Promise&lt;User[]&gt; {
    return await prisma.user.findMany({
      skip,
      take,
      select: {
        id: true,
        email: true,
        username: true,
        fullName: true,
        isActive: true,
        createdAt: true,
        updatedAt: true
      }
    });
  }
}

// src/controllers/userController.ts
import { Request, Response } from &#39;express&#39;;
import { UserService } from &#39;../services/userService&#39;;
import { logger } from &#39;../utils/logger&#39;;

const userService = new UserService();

export class UserController {
  async createUser(req: Request, res: Response) {
    try {
      const user = await userService.createUser(req.body);
      
      logger.info(&#39;User created successfully&#39;, { userId: user.id });
      
      res.status(201).json({
        success: true,
        message: &#39;User created successfully&#39;,
        data: user
      });
    } catch (error) {
      logger.error(&#39;Error creating user&#39;, { error: error.message });
      
      res.status(400).json({
        success: false,
        message: error.message || &#39;Failed to create user&#39;
      });
    }
  }

  async getUser(req: Request, res: Response) {
    try {
      const { id } = req.params;
      const user = await userService.getUserById(id);

      if (!user) {
        return res.status(404).json({
          success: false,
          message: &#39;User not found&#39;
        });
      }

      res.json({
        success: true,
        data: user
      });
    } catch (error) {
      logger.error(&#39;Error fetching user&#39;, { error: error.message });
      
      res.status(500).json({
        success: false,
        message: &#39;Internal server error&#39;
      });
    }
  }

  async getCurrentUser(req: Request, res: Response) {
    try {
      const user = await userService.getUserById(req.user!.userId);

      if (!user) {
        return res.status(404).json({
          success: false,
          message: &#39;User not found&#39;
        });
      }

      res.json({
        success: true,
        data: user
      });
    } catch (error) {
      logger.error(&#39;Error fetching current user&#39;, { error: error.message });
      
      res.status(500).json({
        success: false,
        message: &#39;Internal server error&#39;
      });
    }
  }

  async loginUser(req: Request, res: Response) {
    try {
      const { email, password } = req.body;
      const token = await userService.authenticateUser(email, password);

      if (!token) {
        return res.status(401).json({
          success: false,
          message: &#39;Invalid email or password&#39;
        });
      }

      res.json({
        success: true,
        message: &#39;Login successful&#39;,
        data: { token }
      });
    } catch (error) {
      logger.error(&#39;Error during login&#39;, { error: error.message });
      
      res.status(500).json({
        success: false,
        message: &#39;Internal server error&#39;
      });
    }
  }
}
```

### 4. Testing Implementation

Comprehensive testing setup:

**FastAPI Tests**
```python
# tests/conftest.py
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool

from app.main import app
from app.core.database import Base, get_db
from app.core.config import settings

# Test database
SQLALCHEMY_DATABASE_URL = &quot;sqlite:///./test.db&quot;
engine = create_engine(
    SQLALCHEMY_DATABASE_URL,
    connect_args={&quot;check_same_thread&quot;: False},
    poolclass=StaticPool,
)
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

def override_get_db():
    try:
        db = TestingSessionLocal()
        yield db
    finally:
        db.close()

app.dependency_overrides[get_db] = override_get_db

@pytest.fixture(scope=&quot;session&quot;)
def db_engine():
    Base.metadata.create_all(bind=engine)
    yield engine
    Base.metadata.drop_all(bind=engine)

@pytest.fixture(scope=&quot;function&quot;)
def db_session(db_engine):
    connection = db_engine.connect()
    transaction = connection.begin()
    session = TestingSessionLocal(bind=connection)
    
    yield session
    
    session.close()
    transaction.rollback()
    connection.close()

@pytest.fixture(scope=&quot;module&quot;)
def client():
    with TestClient(app) as test_client:
        yield test_client

# tests/test_users.py
import pytest
from fastapi.testclient import TestClient

def test_create_user(client: TestClient):
    &quot;&quot;&quot;Test user creation&quot;&quot;&quot;
    user_data = {
        &quot;email&quot;: &quot;test@example.com&quot;,
        &quot;username&quot;: &quot;testuser&quot;,
        &quot;password&quot;: &quot;testpassword123&quot;,
        &quot;full_name&quot;: &quot;Test User&quot;
    }
    
    response = client.post(&quot;/api/v1/users/&quot;, json=user_data)
    assert response.status_code == 201
    
    data = response.json()
    assert data[&quot;email&quot;] == user_data[&quot;email&quot;]
    assert data[&quot;username&quot;] == user_data[&quot;username&quot;]
    assert &quot;id&quot; in data
    assert &quot;hashed_password&quot; not in data

def test_create_user_duplicate_email(client: TestClient):
    &quot;&quot;&quot;Test creating user with duplicate email&quot;&quot;&quot;
    user_data = {
        &quot;email&quot;: &quot;duplicate@example.com&quot;,
        &quot;username&quot;: &quot;user1&quot;,
        &quot;password&quot;: &quot;password123&quot;
    }
    
    # Create first user
    response1 = client.post(&quot;/api/v1/users/&quot;, json=user_data)
    assert response1.status_code == 201
    
    # Try to create second user with same email
    user_data[&quot;username&quot;] = &quot;user2&quot;
    response2 = client.post(&quot;/api/v1/users/&quot;, json=user_data)
    assert response2.status_code == 400
    assert &quot;already registered&quot; in response2.json()[&quot;detail&quot;]

def test_get_user_unauthorized(client: TestClient):
    &quot;&quot;&quot;Test accessing protected endpoint without token&quot;&quot;&quot;
    response = client.get(&quot;/api/v1/users/me&quot;)
    assert response.status_code == 401

@pytest.mark.asyncio
async def test_user_authentication_flow(client: TestClient):
    &quot;&quot;&quot;Test complete authentication flow&quot;&quot;&quot;
    # Create user
    user_data = {
        &quot;email&quot;: &quot;auth@example.com&quot;,
        &quot;username&quot;: &quot;authuser&quot;,
        &quot;password&quot;: &quot;authpassword123&quot;
    }
    
    create_response = client.post(&quot;/api/v1/users/&quot;, json=user_data)
    assert create_response.status_code == 201
    
    # Login
    login_data = {
        &quot;email&quot;: user_data[&quot;email&quot;],
        &quot;password&quot;: user_data[&quot;password&quot;]
    }
    login_response = client.post(&quot;/api/v1/auth/login&quot;, json=login_data)
    assert login_response.status_code == 200
    
    token = login_response.json()[&quot;access_token&quot;]
    
    # Access protected endpoint
    headers = {&quot;Authorization&quot;: f&quot;Bearer {token}&quot;}
    profile_response = client.get(&quot;/api/v1/users/me&quot;, headers=headers)
    assert profile_response.status_code == 200
    
    profile_data = profile_response.json()
    assert profile_data[&quot;email&quot;] == user_data[&quot;email&quot;]
```

### 5. Deployment Configuration

**Docker Configuration**
```dockerfile
# Dockerfile (FastAPI)
FROM python:3.11-slim

WORKDIR /app

# Install system dependencies
RUN apt-get update &amp;&amp; apt-get install -y \
    gcc \
    &amp;&amp; rm -rf /var/lib/apt/lists/*

# Install Python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy application
COPY . .

# Create non-root user
RUN adduser --disabled-password --gecos &#39;&#39; appuser
RUN chown -R appuser:appuser /app
USER appuser

# Health check
HEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:8000/health || exit 1

EXPOSE 8000

CMD [&quot;uvicorn&quot;, &quot;app.main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]
```

**Docker Compose**
```yaml
# docker-compose.yml
version: &#39;3.8&#39;

services:
  api:
    build: .
    ports:
      - &quot;8000:8000&quot;
    environment:
      - DATABASE_URL=postgresql://postgres:password@db:5432/appdb
      - REDIS_URL=redis://redis:6379
    depends_on:
      - db
      - redis
    volumes:
      - ./app:/app/app
    restart: unless-stopped

  db:
    image: postgres:15
    environment:
      - POSTGRES_DB=appdb
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=password
    volumes:
      - postgres_data:/var/lib/postgresql/data
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql
    ports:
      - &quot;5432:5432&quot;
    restart: unless-stopped

  redis:
    image: redis:7-alpine
    ports:
      - &quot;6379:6379&quot;
    volumes:
      - redis_data:/data
    restart: unless-stopped

  nginx:
    image: nginx:alpine
    ports:
      - &quot;80:80&quot;
      - &quot;443:443&quot;
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
      - ./ssl:/etc/nginx/ssl
    depends_on:
      - api
    restart: unless-stopped

volumes:
  postgres_data:
  redis_data:
```

### 6. CI/CD Pipeline

**GitHub Actions Workflow**
```yaml
# .github/workflows/api.yml
name: API CI/CD

on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  test:
    runs-on: ubuntu-latest
    
    services:
      postgres:
        image: postgres:15
        env:
          POSTGRES_PASSWORD: postgres
          POSTGRES_DB: test_db
        options: &gt;-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
        ports:
          - 5432:5432
      
      redis:
        image: redis:7
        options: &gt;-
          --health-cmd &quot;redis-cli ping&quot;
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
        ports:
          - 6379:6379

    steps:
    - uses: actions/checkout@v4
    
    - name: Set up Python
      uses: actions/setup-python@v4
      with:
        python-version: &#39;3.11&#39;
    
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install -r requirements.txt
        pip install -r requirements-dev.txt
    
    - name: Run linting
      run: |
        flake8 app tests
        black --check app tests
        isort --check-only app tests
    
    - name: Run type checking
      run: mypy app
    
    - name: Run security scan
      run: bandit -r app
    
    - name: Run tests
      env:
        DATABASE_URL: postgresql://postgres:postgres@localhost:5432/test_db
        REDIS_URL: redis://localhost:6379
      run: |
        pytest tests/ -v --cov=app --cov-report=xml
    
    - name: Upload coverage
      uses: codecov/codecov-action@v3
      with:
        file: ./coverage.xml

  build:
    needs: test
    runs-on: ubuntu-latest
    if: github.event_name == &#39;push&#39;
    
    steps:
    - uses: actions/checkout@v4
    
    - name: Set up Docker Buildx
      uses: docker/setup-buildx-action@v3
    
    - name: Log in to Container Registry
      uses: docker/login-action@v3
      with:
        registry: ${{ env.REGISTRY }}
        username: ${{ github.actor }}
        password: ${{ secrets.GITHUB_TOKEN }}
    
    - name: Extract metadata
      id: meta
      uses: docker/metadata-action@v5
      with:
        images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
        tags: |
          type=ref,event=branch
          type=ref,event=pr
          type=sha
    
    - name: Build and push Docker image
      uses: docker/build-push-action@v5
      with:
        context: .
        push: true
        tags: ${{ steps.meta.outputs.tags }}
        labels: ${{ steps.meta.outputs.labels }}
        cache-from: type=gha
        cache-to: type=gha,mode=max

  deploy:
    needs: build
    runs-on: ubuntu-latest
    if: github.ref == &#39;refs/heads/main&#39;
    
    steps:
    - name: Deploy to staging
      run: |
        echo &quot;Deploying to staging environment&quot;
        # Add deployment commands here
```

### 7. Monitoring and Observability

**Prometheus Metrics**
```python
# app/core/metrics.py
from prometheus_client import Counter, Histogram, Gauge, generate_latest
from fastapi import Request
import time

# Metrics
REQUEST_COUNT = Counter(
    &#39;http_requests_total&#39;,
    &#39;Total HTTP requests&#39;,
    [&#39;method&#39;, &#39;endpoint&#39;, &#39;status&#39;]
)

REQUEST_DURATION = Histogram(
    &#39;http_request_duration_seconds&#39;,
    &#39;HTTP request duration&#39;,
    [&#39;method&#39;, &#39;endpoint&#39;]
)

ACTIVE_CONNECTIONS = Gauge(
    &#39;active_connections&#39;,
    &#39;Active connections&#39;
)

async def record_metrics(request: Request, call_next):
    &quot;&quot;&quot;Record metrics for each request&quot;&quot;&quot;
    start_time = time.time()
    
    ACTIVE_CONNECTIONS.inc()
    
    try:
        response = await call_next(request)
        
        # Record metrics
        REQUEST_COUNT.labels(
            method=request.method,
            endpoint=request.url.path,
            status=response.status_code
        ).inc()
        
        REQUEST_DURATION.labels(
            method=request.method,
            endpoint=request.url.path
        ).observe(time.time() - start_time)
        
        return response
    
    finally:
        ACTIVE_CONNECTIONS.dec()

@app.get(&quot;/metrics&quot;)
async def metrics():
    &quot;&quot;&quot;Prometheus metrics endpoint&quot;&quot;&quot;
    return Response(
        generate_latest(),
        media_type=&quot;text/plain&quot;
    )
```

## Cross-Command Integration

This command integrates seamlessly with other Claude Code commands to create complete development workflows:

### 1. Complete API Development Workflow

**Standard Development Pipeline:**
```bash
# 1. Start with API scaffold
/api-scaffold &quot;User management API with FastAPI, PostgreSQL, and JWT auth&quot;

# 2. Set up comprehensive testing
/test-harness &quot;FastAPI API with unit, integration, and load testing using pytest and locust&quot;

# 3. Security validation
/security-scan &quot;FastAPI application with authentication endpoints&quot;

# 4. Container optimization
/docker-optimize &quot;FastAPI application with PostgreSQL and Redis dependencies&quot;

# 5. Kubernetes deployment
/k8s-manifest &quot;FastAPI microservice with PostgreSQL, Redis, and ingress&quot;

# 6. Frontend integration (if needed)
/frontend-optimize &quot;React application connecting to FastAPI backend&quot;
```

### 2. Database-First Development

**When starting with existing data:**
```bash
# 1. Handle database migrations first
/db-migrate &quot;PostgreSQL schema migration from legacy system to modern structure&quot;

# 2. Generate API based on migrated schema
/api-scaffold &quot;REST API for migrated PostgreSQL schema with auto-generated models&quot;

# 3. Continue with standard pipeline...
```

### 3. Microservices Architecture

**For distributed systems:**
```bash
# Generate multiple related APIs
/api-scaffold &quot;User service with authentication and profile management&quot;
/api-scaffold &quot;Order service with payment processing and inventory&quot;
/api-scaffold &quot;Notification service with email and push notifications&quot;

# Containerize all services
/docker-optimize &quot;Microservices architecture with service discovery&quot;

# Deploy as distributed system
/k8s-manifest &quot;Microservices deployment with service mesh and monitoring&quot;
```

### 4. Integration with Generated Code

**Test Integration Setup:**
```yaml
# After running /api-scaffold, use this with /test-harness
test_config:
  api_base_url: &quot;http://localhost:8000&quot;
  test_database: &quot;postgresql://test:test@localhost:5432/test_db&quot;
  authentication:
    test_user: &quot;test@example.com&quot;
    test_password: &quot;testpassword123&quot;
  
  endpoints_to_test:
    - POST /api/v1/users/
    - POST /api/v1/auth/login
    - GET /api/v1/users/me
    - GET /api/v1/users/{id}
```

**Security Scan Configuration:**
```yaml
# Configuration for /security-scan after API scaffold
security_scan:
  target: &quot;localhost:8000&quot;
  authentication_endpoints:
    - &quot;/api/v1/auth/login&quot;
    - &quot;/api/v1/auth/refresh&quot;
  protected_endpoints:
    - &quot;/api/v1/users/me&quot;
    - &quot;/api/v1/users/{id}&quot;
  vulnerability_tests:
    - jwt_token_validation
    - sql_injection
    - xss_prevention
    - rate_limiting
```

**Docker Integration:**
```dockerfile
# Generated Dockerfile can be optimized with /docker-optimize
# Multi-stage build for FastAPI application
FROM python:3.11-slim as builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --user -r requirements.txt

FROM python:3.11-slim as runtime
WORKDIR /app
COPY --from=builder /root/.local /root/.local
COPY . .
ENV PATH=/root/.local/bin:$PATH
CMD [&quot;uvicorn&quot;, &quot;app.main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]
```

**Kubernetes Deployment:**
```yaml
# Use this configuration with /k8s-manifest
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: api
  template:
    metadata:
      labels:
        app: api
    spec:
      containers:
      - name: api
        image: api:latest
        ports:
        - containerPort: 8000
        env:
        - name: DATABASE_URL
          valueFrom:
            secretKeyRef:
              name: api-secrets
              key: database-url
        - name: JWT_SECRET
          valueFrom:
            secretKeyRef:
              name: api-secrets
              key: jwt-secret
        livenessProbe:
          httpGet:
            path: /health
            port: 8000
          initialDelaySeconds: 30
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /ready
            port: 8000
          initialDelaySeconds: 5
          periodSeconds: 5
```

### 5. CI/CD Pipeline Integration

**Complete pipeline using multiple commands:**
```yaml
name: Full Stack CI/CD

on:
  push:
    branches: [main]

jobs:
  api-test:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4
    
    # Test API (generated by /api-scaffold)
    - name: Run API tests
      run: |
        # Use test configuration from /test-harness
        pytest tests/ -v --cov=app
    
    # Security scan (from /security-scan)
    - name: Security scan
      run: |
        bandit -r app/
        safety check
    
    # Build optimized container (from /docker-optimize)
    - name: Build container
      run: |
        docker build -f Dockerfile.optimized -t api:${{ github.sha }} .
    
    # Deploy to Kubernetes (from /k8s-manifest)
    - name: Deploy to staging
      run: |
        kubectl apply -f k8s/staging/
        kubectl set image deployment/api-deployment api=api:${{ github.sha }}
```

### 6. Frontend-Backend Integration

**When building full-stack applications:**
```bash
# 1. Backend API
/api-scaffold &quot;REST API with user management and data operations&quot;

# 2. Frontend application
/frontend-optimize &quot;React SPA with API integration, authentication, and state management&quot;

# 3. Integration testing
/test-harness &quot;End-to-end testing for React frontend and FastAPI backend&quot;

# 4. Unified deployment
/k8s-manifest &quot;Full-stack deployment with API, frontend, and database&quot;
```

**Frontend API Integration Code:**
```typescript
// Generated API client for frontend
// Use this pattern with /frontend-optimize
export class APIClient {
  private baseURL: string;
  private token: string | null = null;

  constructor(baseURL: string) {
    this.baseURL = baseURL;
  }

  setAuthToken(token: string) {
    this.token = token;
  }

  private async request&lt;T&gt;(
    endpoint: string, 
    options: RequestInit = {}
  ): Promise&lt;T&gt; {
    const url = `${this.baseURL}${endpoint}`;
    const headers = {
      &#39;Content-Type&#39;: &#39;application/json&#39;,
      ...(this.token &amp;&amp; { Authorization: `Bearer ${this.token}` }),
      ...options.headers,
    };

    const response = await fetch(url, {
      ...options,
      headers,
    });

    if (!response.ok) {
      throw new Error(`API Error: ${response.statusText}`);
    }

    return response.json();
  }

  // User management methods (matching API scaffold)
  async createUser(userData: CreateUserRequest): Promise&lt;User&gt; {
    return this.request&lt;User&gt;(&#39;/api/v1/users/&#39;, {
      method: &#39;POST&#39;,
      body: JSON.stringify(userData),
    });
  }

  async login(credentials: LoginRequest): Promise&lt;AuthResponse&gt; {
    return this.request&lt;AuthResponse&gt;(&#39;/api/v1/auth/login&#39;, {
      method: &#39;POST&#39;,
      body: JSON.stringify(credentials),
    });
  }

  async getCurrentUser(): Promise&lt;User&gt; {
    return this.request&lt;User&gt;(&#39;/api/v1/users/me&#39;);
  }
}
```

### 7. Monitoring and Observability Integration

**Complete observability stack:**
```bash
# After API deployment, add monitoring
/api-scaffold &quot;Monitoring endpoints with Prometheus metrics and health checks&quot;

# Use with Kubernetes monitoring
/k8s-manifest &quot;Kubernetes deployment with Prometheus, Grafana, and alerting&quot;
```

This integrated approach ensures all components work together seamlessly, creating a production-ready system with proper testing, security, deployment, and monitoring.

## Validation Checklist

- [ ] Framework selected based on requirements
- [ ] Project structure follows best practices
- [ ] Authentication and authorization implemented
- [ ] Input validation and sanitization in place
- [ ] Rate limiting configured
- [ ] Error handling comprehensive
- [ ] Logging and monitoring setup
- [ ] Tests written and passing
- [ ] Security measures implemented
- [ ] API documentation generated
- [ ] Deployment configuration ready
- [ ] CI/CD pipeline configured

Focus on creating production-ready APIs with proper architecture, security, testing, and operational concerns addressed from the start.</pre>
                  </div>
                </div>
              </div>
          </div>

        </div>
      </div>
    </div>
  </div>
</div>

</template></turbo-stream>