{"aiPlatform":"claude-code@2025.06","category":"api-design","commandName":"/api-scaffold","content":"---\nname: API Scaffold Generator\ndescription: Production-ready API development tool that creates scalable REST APIs with modern frameworks. Generates complete implementations including models, validation, security, testing, and deployment configuration following industry best practices.\nallowed_tools:\n  - filesystem      # API file generation\n  - memory          # API pattern storage\ntags:\n  - api-development\n  - scaffolding\n  - rest-api\n  - backend\n  - microservices\ncategory: development\nversion: 2.0.0\nauthor: AI Commands Team\n---\n\n# API Scaffold Generator\n\nYou 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.\n\n## Context\nThe 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.\n\n## Requirements\n$ARGUMENTS\n\n## Instructions\n\n### 1. API Framework Selection\n\nChoose the appropriate framework based on requirements:\n\n**Framework Comparison Matrix**\n```python\ndef select_framework(requirements):\n    \"\"\"Select optimal API framework based on requirements\"\"\"\n    \n    frameworks = {\n        'fastapi': {\n            'best_for': ['high_performance', 'async_operations', 'type_safety', 'modern_python'],\n            'strengths': ['Auto OpenAPI docs', 'Type hints', 'Async support', 'Fast performance'],\n            'use_cases': ['Microservices', 'Data APIs', 'ML APIs', 'Real-time systems'],\n            'example_stack': 'FastAPI + Pydantic + SQLAlchemy + PostgreSQL'\n        },\n        'django_rest': {\n            'best_for': ['rapid_development', 'orm_integration', 'admin_interface', 'large_teams'],\n            'strengths': ['Batteries included', 'ORM', 'Admin panel', 'Mature ecosystem'],\n            'use_cases': ['CRUD applications', 'Content management', 'Enterprise systems'],\n            'example_stack': 'Django + DRF + PostgreSQL + Redis'\n        },\n        'express': {\n            'best_for': ['node_ecosystem', 'real_time', 'frontend_integration', 'javascript_teams'],\n            'strengths': ['NPM ecosystem', 'JSON handling', 'WebSocket support', 'Fast development'],\n            'use_cases': ['Real-time apps', 'API gateways', 'Serverless functions'],\n            'example_stack': 'Express + TypeScript + Prisma + PostgreSQL'\n        },\n        'spring_boot': {\n            'best_for': ['enterprise', 'java_teams', 'complex_business_logic', 'microservices'],\n            'strengths': ['Enterprise features', 'Dependency injection', 'Security', 'Monitoring'],\n            'use_cases': ['Enterprise APIs', 'Financial systems', 'Complex microservices'],\n            'example_stack': 'Spring Boot + JPA + PostgreSQL + Redis'\n        }\n    }\n    \n    # Selection logic based on requirements\n    if 'high_performance' in requirements:\n        return frameworks['fastapi']\n    elif 'enterprise' in requirements:\n        return frameworks['spring_boot']\n    elif 'rapid_development' in requirements:\n        return frameworks['django_rest']\n    elif 'real_time' in requirements:\n        return frameworks['express']\n    \n    return frameworks['fastapi']  # Default recommendation\n```\n\n### 2. FastAPI Implementation\n\nComplete FastAPI API implementation:\n\n**Project Structure**\n```\nproject/\n├── app/\n│   ├── __init__.py\n│   ├── main.py\n│   ├── core/\n│   │   ├── config.py\n│   │   ├── security.py\n│   │   └── database.py\n│   ├── api/\n│   │   ├── __init__.py\n│   │   ├── deps.py\n│   │   └── v1/\n│   │       ├── __init__.py\n│   │       ├── endpoints/\n│   │       │   ├── users.py\n│   │       │   └── items.py\n│   │       └── api.py\n│   ├── models/\n│   │   ├── __init__.py\n│   │   ├── user.py\n│   │   └── item.py\n│   ├── schemas/\n│   │   ├── __init__.py\n│   │   ├── user.py\n│   │   └── item.py\n│   ├── services/\n│   │   ├── __init__.py\n│   │   ├── user_service.py\n│   │   └── item_service.py\n│   └── tests/\n│       ├── conftest.py\n│       ├── test_users.py\n│       └── test_items.py\n├── alembic/\n├── requirements.txt\n├── Dockerfile\n└── docker-compose.yml\n```\n\n**Core Configuration**\n```python\n# app/core/config.py\nfrom pydantic import BaseSettings, validator\nfrom typing import Optional, Dict, Any\nimport secrets\n\nclass Settings(BaseSettings):\n    API_V1_STR: str = \"/api/v1\"\n    SECRET_KEY: str = secrets.token_urlsafe(32)\n    ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8  # 8 days\n    SERVER_NAME: str = \"localhost\"\n    SERVER_HOST: str = \"0.0.0.0\"\n    \n    # Database\n    POSTGRES_SERVER: str = \"localhost\"\n    POSTGRES_USER: str = \"postgres\"\n    POSTGRES_PASSWORD: str = \"\"\n    POSTGRES_DB: str = \"app\"\n    DATABASE_URL: Optional[str] = None\n    \n    @validator(\"DATABASE_URL\", pre=True)\n    def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Any:\n        if isinstance(v, str):\n            return v\n        return f\"postgresql://{values.get('POSTGRES_USER')}:{values.get('POSTGRES_PASSWORD')}@{values.get('POSTGRES_SERVER')}/{values.get('POSTGRES_DB')}\"\n    \n    # Redis\n    REDIS_URL: str = \"redis://localhost:6379\"\n    \n    # Security\n    BACKEND_CORS_ORIGINS: list = [\"http://localhost:3000\", \"http://localhost:8000\"]\n    \n    # Rate Limiting\n    RATE_LIMIT_REQUESTS: int = 100\n    RATE_LIMIT_WINDOW: int = 60\n    \n    # Monitoring\n    SENTRY_DSN: Optional[str] = None\n    LOG_LEVEL: str = \"INFO\"\n    \n    class Config:\n        env_file = \".env\"\n\nsettings = Settings()\n```\n\n**Database Setup**\n```python\n# app/core/database.py\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.pool import StaticPool\nimport redis\n\nfrom app.core.config import settings\n\n# PostgreSQL\nengine = create_engine(\n    settings.DATABASE_URL,\n    poolclass=StaticPool,\n    pool_size=20,\n    max_overflow=30,\n    pool_pre_ping=True,\n    echo=settings.LOG_LEVEL == \"DEBUG\"\n)\n\nSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)\nBase = declarative_base()\n\n# Redis\nredis_client = redis.from_url(settings.REDIS_URL, decode_responses=True)\n\ndef get_db():\n    \"\"\"Dependency to get database session\"\"\"\n    db = SessionLocal()\n    try:\n        yield db\n    finally:\n        db.close()\n\ndef get_redis():\n    \"\"\"Dependency to get Redis connection\"\"\"\n    return redis_client\n```\n\n**Security Implementation**\n```python\n# app/core/security.py\nfrom datetime import datetime, timedelta\nfrom typing import Optional\nimport jwt\nfrom passlib.context import CryptContext\nfrom fastapi import HTTPException, status\nfrom fastapi.security import HTTPBearer, HTTPAuthorizationCredentials\n\nfrom app.core.config import settings\n\npwd_context = CryptContext(schemes=[\"bcrypt\"], deprecated=\"auto\")\nsecurity = HTTPBearer()\n\ndef create_access_token(data: dict, expires_delta: Optional[timedelta] = None):\n    \"\"\"Create JWT access token\"\"\"\n    to_encode = data.copy()\n    if expires_delta:\n        expire = datetime.utcnow() + expires_delta\n    else:\n        expire = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)\n    \n    to_encode.update({\"exp\": expire})\n    encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=\"HS256\")\n    return encoded_jwt\n\ndef verify_token(credentials: HTTPAuthorizationCredentials) -> dict:\n    \"\"\"Verify JWT token\"\"\"\n    try:\n        payload = jwt.decode(\n            credentials.credentials, \n            settings.SECRET_KEY, \n            algorithms=[\"HS256\"]\n        )\n        username: str = payload.get(\"sub\")\n        if username is None:\n            raise HTTPException(\n                status_code=status.HTTP_401_UNAUTHORIZED,\n                detail=\"Could not validate credentials\",\n                headers={\"WWW-Authenticate\": \"Bearer\"},\n            )\n        return payload\n    except jwt.PyJWTError:\n        raise HTTPException(\n            status_code=status.HTTP_401_UNAUTHORIZED,\n            detail=\"Could not validate credentials\",\n            headers={\"WWW-Authenticate\": \"Bearer\"},\n        )\n\ndef verify_password(plain_password: str, hashed_password: str) -> bool:\n    \"\"\"Verify password against hash\"\"\"\n    return pwd_context.verify(plain_password, hashed_password)\n\ndef get_password_hash(password: str) -> str:\n    \"\"\"Generate password hash\"\"\"\n    return pwd_context.hash(password)\n```\n\n**Models Implementation**\n```python\n# app/models/user.py\nfrom sqlalchemy import Column, Integer, String, Boolean, DateTime, Text\nfrom sqlalchemy.sql import func\nfrom sqlalchemy.orm import relationship\n\nfrom app.core.database import Base\n\nclass User(Base):\n    __tablename__ = \"users\"\n    \n    id = Column(Integer, primary_key=True, index=True)\n    email = Column(String, unique=True, index=True, nullable=False)\n    username = Column(String, unique=True, index=True, nullable=False)\n    hashed_password = Column(String, nullable=False)\n    full_name = Column(String)\n    is_active = Column(Boolean, default=True)\n    is_superuser = Column(Boolean, default=False)\n    created_at = Column(DateTime(timezone=True), server_default=func.now())\n    updated_at = Column(DateTime(timezone=True), onupdate=func.now())\n    \n    # Relationships\n    items = relationship(\"Item\", back_populates=\"owner\")\n\n# app/models/item.py\nfrom sqlalchemy import Column, Integer, String, Boolean, DateTime, Text, ForeignKey\nfrom sqlalchemy.sql import func\nfrom sqlalchemy.orm import relationship\n\nfrom app.core.database import Base\n\nclass Item(Base):\n    __tablename__ = \"items\"\n    \n    id = Column(Integer, primary_key=True, index=True)\n    title = Column(String, index=True, nullable=False)\n    description = Column(Text)\n    is_active = Column(Boolean, default=True)\n    owner_id = Column(Integer, ForeignKey(\"users.id\"))\n    created_at = Column(DateTime(timezone=True), server_default=func.now())\n    updated_at = Column(DateTime(timezone=True), onupdate=func.now())\n    \n    # Relationships\n    owner = relationship(\"User\", back_populates=\"items\")\n```\n\n**Pydantic Schemas**\n```python\n# app/schemas/user.py\nfrom pydantic import BaseModel, EmailStr, validator\nfrom typing import Optional\nfrom datetime import datetime\n\nclass UserBase(BaseModel):\n    email: EmailStr\n    username: str\n    full_name: Optional[str] = None\n\nclass UserCreate(UserBase):\n    password: str\n    \n    @validator('password')\n    def validate_password(cls, v):\n        if len(v) < 8:\n            raise ValueError('Password must be at least 8 characters')\n        return v\n\nclass UserUpdate(BaseModel):\n    email: Optional[EmailStr] = None\n    username: Optional[str] = None\n    full_name: Optional[str] = None\n    is_active: Optional[bool] = None\n\nclass UserInDB(UserBase):\n    id: int\n    is_active: bool\n    is_superuser: bool\n    created_at: datetime\n    updated_at: Optional[datetime]\n    \n    class Config:\n        orm_mode = True\n\nclass User(UserInDB):\n    pass\n\n# app/schemas/item.py\nfrom pydantic import BaseModel, validator\nfrom typing import Optional\nfrom datetime import datetime\n\nclass ItemBase(BaseModel):\n    title: str\n    description: Optional[str] = None\n\nclass ItemCreate(ItemBase):\n    @validator('title')\n    def validate_title(cls, v):\n        if len(v.strip()) < 3:\n            raise ValueError('Title must be at least 3 characters')\n        return v.strip()\n\nclass ItemUpdate(BaseModel):\n    title: Optional[str] = None\n    description: Optional[str] = None\n    is_active: Optional[bool] = None\n\nclass ItemInDB(ItemBase):\n    id: int\n    is_active: bool\n    owner_id: int\n    created_at: datetime\n    updated_at: Optional[datetime]\n    \n    class Config:\n        orm_mode = True\n\nclass Item(ItemInDB):\n    pass\n```\n\n**Service Layer**\n```python\n# app/services/user_service.py\nfrom typing import Optional, List\nfrom sqlalchemy.orm import Session\nfrom fastapi import HTTPException, status\n\nfrom app.models.user import User\nfrom app.schemas.user import UserCreate, UserUpdate\nfrom app.core.security import get_password_hash, verify_password\n\nclass UserService:\n    def __init__(self, db: Session):\n        self.db = db\n    \n    def get_user(self, user_id: int) -> Optional[User]:\n        \"\"\"Get user by ID\"\"\"\n        return self.db.query(User).filter(User.id == user_id).first()\n    \n    def get_user_by_email(self, email: str) -> Optional[User]:\n        \"\"\"Get user by email\"\"\"\n        return self.db.query(User).filter(User.email == email).first()\n    \n    def get_users(self, skip: int = 0, limit: int = 100) -> List[User]:\n        \"\"\"Get list of users\"\"\"\n        return self.db.query(User).offset(skip).limit(limit).all()\n    \n    def create_user(self, user_create: UserCreate) -> User:\n        \"\"\"Create new user\"\"\"\n        # Check if user exists\n        if self.get_user_by_email(user_create.email):\n            raise HTTPException(\n                status_code=status.HTTP_400_BAD_REQUEST,\n                detail=\"Email already registered\"\n            )\n        \n        # Create user\n        hashed_password = get_password_hash(user_create.password)\n        db_user = User(\n            email=user_create.email,\n            username=user_create.username,\n            full_name=user_create.full_name,\n            hashed_password=hashed_password\n        )\n        self.db.add(db_user)\n        self.db.commit()\n        self.db.refresh(db_user)\n        return db_user\n    \n    def update_user(self, user_id: int, user_update: UserUpdate) -> User:\n        \"\"\"Update user\"\"\"\n        db_user = self.get_user(user_id)\n        if not db_user:\n            raise HTTPException(\n                status_code=status.HTTP_404_NOT_FOUND,\n                detail=\"User not found\"\n            )\n        \n        update_data = user_update.dict(exclude_unset=True)\n        for field, value in update_data.items():\n            setattr(db_user, field, value)\n        \n        self.db.commit()\n        self.db.refresh(db_user)\n        return db_user\n    \n    def authenticate_user(self, email: str, password: str) -> Optional[User]:\n        \"\"\"Authenticate user\"\"\"\n        user = self.get_user_by_email(email)\n        if not user or not verify_password(password, user.hashed_password):\n            return None\n        return user\n```\n\n**Rate Limiting Middleware**\n```python\n# app/core/rate_limiting.py\nimport time\nfrom typing import Callable\nfrom fastapi import Request, HTTPException, status\nfrom fastapi.responses import JSONResponse\nimport redis\n\nfrom app.core.config import settings\nfrom app.core.database import get_redis\n\nclass RateLimiter:\n    def __init__(self, redis_client: redis.Redis):\n        self.redis = redis_client\n        self.requests = settings.RATE_LIMIT_REQUESTS\n        self.window = settings.RATE_LIMIT_WINDOW\n    \n    async def __call__(self, request: Request, call_next: Callable):\n        # Get client identifier\n        client_ip = request.client.host\n        user_id = getattr(request.state, 'user_id', None)\n        key = f\"rate_limit:{user_id or client_ip}\"\n        \n        # Check rate limit\n        current = self.redis.get(key)\n        if current is None:\n            # First request in window\n            self.redis.setex(key, self.window, 1)\n        else:\n            current = int(current)\n            if current >= self.requests:\n                raise HTTPException(\n                    status_code=status.HTTP_429_TOO_MANY_REQUESTS,\n                    detail=f\"Rate limit exceeded. Try again in {self.redis.ttl(key)} seconds\",\n                    headers={\"Retry-After\": str(self.redis.ttl(key))}\n                )\n            self.redis.incr(key)\n        \n        response = await call_next(request)\n        \n        # Add rate limit headers\n        remaining = max(0, self.requests - int(self.redis.get(key) or 0))\n        response.headers[\"X-RateLimit-Limit\"] = str(self.requests)\n        response.headers[\"X-RateLimit-Remaining\"] = str(remaining)\n        response.headers[\"X-RateLimit-Reset\"] = str(int(time.time()) + self.redis.ttl(key))\n        \n        return response\n```\n\n**API Endpoints**\n```python\n# app/api/v1/endpoints/users.py\nfrom typing import List\nfrom fastapi import APIRouter, Depends, HTTPException, status\nfrom sqlalchemy.orm import Session\n\nfrom app.core.database import get_db\nfrom app.core.security import verify_token, security\nfrom app.schemas.user import User, UserCreate, UserUpdate\nfrom app.services.user_service import UserService\n\nrouter = APIRouter()\n\n@router.post(\"/\", response_model=User, status_code=status.HTTP_201_CREATED)\nasync def create_user(\n    user_create: UserCreate,\n    db: Session = Depends(get_db)\n):\n    \"\"\"Create new user\"\"\"\n    service = UserService(db)\n    return service.create_user(user_create)\n\n@router.get(\"/me\", response_model=User)\nasync def get_current_user(\n    token: dict = Depends(verify_token),\n    db: Session = Depends(get_db)\n):\n    \"\"\"Get current user profile\"\"\"\n    service = UserService(db)\n    user = service.get_user_by_email(token[\"sub\"])\n    if not user:\n        raise HTTPException(\n            status_code=status.HTTP_404_NOT_FOUND,\n            detail=\"User not found\"\n        )\n    return user\n\n@router.get(\"/{user_id}\", response_model=User)\nasync def get_user(\n    user_id: int,\n    db: Session = Depends(get_db),\n    token: dict = Depends(verify_token)\n):\n    \"\"\"Get user by ID\"\"\"\n    service = UserService(db)\n    user = service.get_user(user_id)\n    if not user:\n        raise HTTPException(\n            status_code=status.HTTP_404_NOT_FOUND,\n            detail=\"User not found\"\n        )\n    return user\n\n@router.put(\"/{user_id}\", response_model=User)\nasync def update_user(\n    user_id: int,\n    user_update: UserUpdate,\n    db: Session = Depends(get_db),\n    token: dict = Depends(verify_token)\n):\n    \"\"\"Update user\"\"\"\n    service = UserService(db)\n    return service.update_user(user_id, user_update)\n\n@router.get(\"/\", response_model=List[User])\nasync def list_users(\n    skip: int = 0,\n    limit: int = 100,\n    db: Session = Depends(get_db),\n    token: dict = Depends(verify_token)\n):\n    \"\"\"List users\"\"\"\n    service = UserService(db)\n    return service.get_users(skip=skip, limit=limit)\n```\n\n**Main Application**\n```python\n# app/main.py\nfrom fastapi import FastAPI, Request\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom fastapi.middleware.trustedhost import TrustedHostMiddleware\nfrom fastapi.responses import JSONResponse\nimport logging\nimport time\nimport uuid\n\nfrom app.core.config import settings\nfrom app.core.rate_limiting import RateLimiter\nfrom app.core.database import get_redis\nfrom app.api.v1.api import api_router\n\n# Configure logging\nlogging.basicConfig(\n    level=getattr(logging, settings.LOG_LEVEL),\n    format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\"\n)\nlogger = logging.getLogger(__name__)\n\n# Create FastAPI app\napp = FastAPI(\n    title=\"Production API\",\n    description=\"A production-ready API with FastAPI\",\n    version=\"1.0.0\",\n    openapi_url=f\"{settings.API_V1_STR}/openapi.json\"\n)\n\n# Middleware\napp.add_middleware(\n    CORSMiddleware,\n    allow_origins=settings.BACKEND_CORS_ORIGINS,\n    allow_credentials=True,\n    allow_methods=[\"*\"],\n    allow_headers=[\"*\"],\n)\n\napp.add_middleware(\n    TrustedHostMiddleware,\n    allowed_hosts=[\"localhost\", \"127.0.0.1\", settings.SERVER_NAME]\n)\n\n# Rate limiting middleware\nrate_limiter = RateLimiter(get_redis())\napp.middleware(\"http\")(rate_limiter)\n\n@app.middleware(\"http\")\nasync def add_process_time_header(request: Request, call_next):\n    \"\"\"Add processing time and correlation ID\"\"\"\n    correlation_id = str(uuid.uuid4())\n    request.state.correlation_id = correlation_id\n    \n    start_time = time.time()\n    response = await call_next(request)\n    process_time = time.time() - start_time\n    \n    response.headers[\"X-Process-Time\"] = str(process_time)\n    response.headers[\"X-Correlation-ID\"] = correlation_id\n    return response\n\n@app.exception_handler(Exception)\nasync def global_exception_handler(request: Request, exc: Exception):\n    \"\"\"Global exception handler\"\"\"\n    correlation_id = getattr(request.state, 'correlation_id', 'unknown')\n    \n    logger.error(\n        f\"Unhandled exception: {exc}\",\n        extra={\"correlation_id\": correlation_id, \"path\": request.url.path}\n    )\n    \n    return JSONResponse(\n        status_code=500,\n        content={\n            \"detail\": \"Internal server error\",\n            \"correlation_id\": correlation_id\n        }\n    )\n\n# Include routers\napp.include_router(api_router, prefix=settings.API_V1_STR)\n\n@app.get(\"/health\")\nasync def health_check():\n    \"\"\"Health check endpoint\"\"\"\n    return {\"status\": \"healthy\", \"timestamp\": time.time()}\n\n@app.get(\"/\")\nasync def root():\n    \"\"\"Root endpoint\"\"\"\n    return {\"message\": \"Welcome to the Production API\"}\n\nif __name__ == \"__main__\":\n    import uvicorn\n    uvicorn.run(\n        \"app.main:app\",\n        host=settings.SERVER_HOST,\n        port=8000,\n        reload=True\n    )\n```\n\n### 3. Express.js Implementation\n\nComplete Express.js TypeScript implementation:\n\n**Project Structure & Setup**\n```typescript\n// package.json\n{\n  \"name\": \"express-api\",\n  \"version\": \"1.0.0\",\n  \"scripts\": {\n    \"dev\": \"nodemon src/index.ts\",\n    \"build\": \"tsc\",\n    \"start\": \"node dist/index.js\",\n    \"test\": \"jest\",\n    \"test:watch\": \"jest --watch\"\n  },\n  \"dependencies\": {\n    \"express\": \"^4.18.2\",\n    \"express-rate-limit\": \"^6.10.0\",\n    \"helmet\": \"^7.0.0\",\n    \"cors\": \"^2.8.5\",\n    \"compression\": \"^1.7.4\",\n    \"morgan\": \"^1.10.0\",\n    \"joi\": \"^17.9.2\",\n    \"jsonwebtoken\": \"^9.0.2\",\n    \"bcryptjs\": \"^2.4.3\",\n    \"prisma\": \"^5.1.0\",\n    \"@prisma/client\": \"^5.1.0\",\n    \"redis\": \"^4.6.7\",\n    \"winston\": \"^3.10.0\"\n  },\n  \"devDependencies\": {\n    \"@types/express\": \"^4.17.17\",\n    \"@types/node\": \"^20.4.5\",\n    \"typescript\": \"^5.1.6\",\n    \"nodemon\": \"^3.0.1\",\n    \"jest\": \"^29.6.1\",\n    \"@types/jest\": \"^29.5.3\",\n    \"supertest\": \"^6.3.3\"\n  }\n}\n\n// src/types/index.ts\nexport interface User {\n  id: string;\n  email: string;\n  username: string;\n  fullName?: string;\n  isActive: boolean;\n  createdAt: Date;\n  updatedAt: Date;\n}\n\nexport interface CreateUserRequest {\n  email: string;\n  username: string;\n  password: string;\n  fullName?: string;\n}\n\nexport interface AuthTokenPayload {\n  userId: string;\n  email: string;\n  iat: number;\n  exp: number;\n}\n\n// src/config/index.ts\nimport { config as dotenvConfig } from 'dotenv';\n\ndotenvConfig();\n\nexport const config = {\n  port: parseInt(process.env.PORT || '3000'),\n  jwtSecret: process.env.JWT_SECRET || 'your-secret-key',\n  jwtExpiresIn: process.env.JWT_EXPIRES_IN || '7d',\n  redisUrl: process.env.REDIS_URL || 'redis://localhost:6379',\n  databaseUrl: process.env.DATABASE_URL || 'postgresql://user:pass@localhost:5432/db',\n  nodeEnv: process.env.NODE_ENV || 'development',\n  corsOrigins: process.env.CORS_ORIGINS?.split(',') || ['http://localhost:3000'],\n  rateLimitMax: parseInt(process.env.RATE_LIMIT_MAX || '100'),\n  rateLimitWindow: parseInt(process.env.RATE_LIMIT_WINDOW_MS || '900000'), // 15 minutes\n};\n\n// src/middleware/validation.ts\nimport { Request, Response, NextFunction } from 'express';\nimport Joi from 'joi';\n\nexport const validateRequest = (schema: Joi.ObjectSchema) => {\n  return (req: Request, res: Response, next: NextFunction) => {\n    const { error } = schema.validate(req.body);\n    \n    if (error) {\n      return res.status(400).json({\n        success: false,\n        message: 'Validation error',\n        details: error.details.map(detail => ({\n          field: detail.path.join('.'),\n          message: detail.message\n        }))\n      });\n    }\n    \n    next();\n  };\n};\n\n// Validation schemas\nexport const userSchemas = {\n  create: Joi.object({\n    email: Joi.string().email().required(),\n    username: Joi.string().alphanum().min(3).max(30).required(),\n    password: Joi.string().min(8).required(),\n    fullName: Joi.string().max(100).optional()\n  }),\n  \n  update: Joi.object({\n    email: Joi.string().email().optional(),\n    username: Joi.string().alphanum().min(3).max(30).optional(),\n    fullName: Joi.string().max(100).optional(),\n    isActive: Joi.boolean().optional()\n  })\n};\n\n// src/middleware/auth.ts\nimport { Request, Response, NextFunction } from 'express';\nimport jwt from 'jsonwebtoken';\nimport { config } from '../config';\nimport { AuthTokenPayload } from '../types';\n\ndeclare global {\n  namespace Express {\n    interface Request {\n      user?: AuthTokenPayload;\n    }\n  }\n}\n\nexport const authenticateToken = (req: Request, res: Response, next: NextFunction) => {\n  const authHeader = req.headers.authorization;\n  const token = authHeader && authHeader.split(' ')[1];\n\n  if (!token) {\n    return res.status(401).json({\n      success: false,\n      message: 'Access token required'\n    });\n  }\n\n  try {\n    const decoded = jwt.verify(token, config.jwtSecret) as AuthTokenPayload;\n    req.user = decoded;\n    next();\n  } catch (error) {\n    return res.status(403).json({\n      success: false,\n      message: 'Invalid or expired token'\n    });\n  }\n};\n\n// src/services/userService.ts\nimport { PrismaClient } from '@prisma/client';\nimport bcrypt from 'bcryptjs';\nimport jwt from 'jsonwebtoken';\nimport { config } from '../config';\nimport { CreateUserRequest, User } from '../types';\n\nconst prisma = new PrismaClient();\n\nexport class UserService {\n  async createUser(userData: CreateUserRequest): Promise<User> {\n    // Check if user exists\n    const existingUser = await prisma.user.findFirst({\n      where: {\n        OR: [\n          { email: userData.email },\n          { username: userData.username }\n        ]\n      }\n    });\n\n    if (existingUser) {\n      throw new Error('User with this email or username already exists');\n    }\n\n    // Hash password\n    const hashedPassword = await bcrypt.hash(userData.password, 12);\n\n    // Create user\n    const user = await prisma.user.create({\n      data: {\n        email: userData.email,\n        username: userData.username,\n        fullName: userData.fullName,\n        hashedPassword,\n        isActive: true\n      }\n    });\n\n    // Remove password from response\n    const { hashedPassword: _, ...userWithoutPassword } = user;\n    return userWithoutPassword as User;\n  }\n\n  async getUserById(id: string): Promise<User | null> {\n    const user = await prisma.user.findUnique({\n      where: { id },\n      select: {\n        id: true,\n        email: true,\n        username: true,\n        fullName: true,\n        isActive: true,\n        createdAt: true,\n        updatedAt: true\n      }\n    });\n\n    return user;\n  }\n\n  async authenticateUser(email: string, password: string): Promise<string | null> {\n    const user = await prisma.user.findUnique({\n      where: { email }\n    });\n\n    if (!user || !await bcrypt.compare(password, user.hashedPassword)) {\n      return null;\n    }\n\n    const token = jwt.sign(\n      { userId: user.id, email: user.email },\n      config.jwtSecret,\n      { expiresIn: config.jwtExpiresIn }\n    );\n\n    return token;\n  }\n\n  async getUsers(skip = 0, take = 10): Promise<User[]> {\n    return await prisma.user.findMany({\n      skip,\n      take,\n      select: {\n        id: true,\n        email: true,\n        username: true,\n        fullName: true,\n        isActive: true,\n        createdAt: true,\n        updatedAt: true\n      }\n    });\n  }\n}\n\n// src/controllers/userController.ts\nimport { Request, Response } from 'express';\nimport { UserService } from '../services/userService';\nimport { logger } from '../utils/logger';\n\nconst userService = new UserService();\n\nexport class UserController {\n  async createUser(req: Request, res: Response) {\n    try {\n      const user = await userService.createUser(req.body);\n      \n      logger.info('User created successfully', { userId: user.id });\n      \n      res.status(201).json({\n        success: true,\n        message: 'User created successfully',\n        data: user\n      });\n    } catch (error) {\n      logger.error('Error creating user', { error: error.message });\n      \n      res.status(400).json({\n        success: false,\n        message: error.message || 'Failed to create user'\n      });\n    }\n  }\n\n  async getUser(req: Request, res: Response) {\n    try {\n      const { id } = req.params;\n      const user = await userService.getUserById(id);\n\n      if (!user) {\n        return res.status(404).json({\n          success: false,\n          message: 'User not found'\n        });\n      }\n\n      res.json({\n        success: true,\n        data: user\n      });\n    } catch (error) {\n      logger.error('Error fetching user', { error: error.message });\n      \n      res.status(500).json({\n        success: false,\n        message: 'Internal server error'\n      });\n    }\n  }\n\n  async getCurrentUser(req: Request, res: Response) {\n    try {\n      const user = await userService.getUserById(req.user!.userId);\n\n      if (!user) {\n        return res.status(404).json({\n          success: false,\n          message: 'User not found'\n        });\n      }\n\n      res.json({\n        success: true,\n        data: user\n      });\n    } catch (error) {\n      logger.error('Error fetching current user', { error: error.message });\n      \n      res.status(500).json({\n        success: false,\n        message: 'Internal server error'\n      });\n    }\n  }\n\n  async loginUser(req: Request, res: Response) {\n    try {\n      const { email, password } = req.body;\n      const token = await userService.authenticateUser(email, password);\n\n      if (!token) {\n        return res.status(401).json({\n          success: false,\n          message: 'Invalid email or password'\n        });\n      }\n\n      res.json({\n        success: true,\n        message: 'Login successful',\n        data: { token }\n      });\n    } catch (error) {\n      logger.error('Error during login', { error: error.message });\n      \n      res.status(500).json({\n        success: false,\n        message: 'Internal server error'\n      });\n    }\n  }\n}\n```\n\n### 4. Testing Implementation\n\nComprehensive testing setup:\n\n**FastAPI Tests**\n```python\n# tests/conftest.py\nimport pytest\nfrom fastapi.testclient import TestClient\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.pool import StaticPool\n\nfrom app.main import app\nfrom app.core.database import Base, get_db\nfrom app.core.config import settings\n\n# Test database\nSQLALCHEMY_DATABASE_URL = \"sqlite:///./test.db\"\nengine = create_engine(\n    SQLALCHEMY_DATABASE_URL,\n    connect_args={\"check_same_thread\": False},\n    poolclass=StaticPool,\n)\nTestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)\n\ndef override_get_db():\n    try:\n        db = TestingSessionLocal()\n        yield db\n    finally:\n        db.close()\n\napp.dependency_overrides[get_db] = override_get_db\n\n@pytest.fixture(scope=\"session\")\ndef db_engine():\n    Base.metadata.create_all(bind=engine)\n    yield engine\n    Base.metadata.drop_all(bind=engine)\n\n@pytest.fixture(scope=\"function\")\ndef db_session(db_engine):\n    connection = db_engine.connect()\n    transaction = connection.begin()\n    session = TestingSessionLocal(bind=connection)\n    \n    yield session\n    \n    session.close()\n    transaction.rollback()\n    connection.close()\n\n@pytest.fixture(scope=\"module\")\ndef client():\n    with TestClient(app) as test_client:\n        yield test_client\n\n# tests/test_users.py\nimport pytest\nfrom fastapi.testclient import TestClient\n\ndef test_create_user(client: TestClient):\n    \"\"\"Test user creation\"\"\"\n    user_data = {\n        \"email\": \"test@example.com\",\n        \"username\": \"testuser\",\n        \"password\": \"testpassword123\",\n        \"full_name\": \"Test User\"\n    }\n    \n    response = client.post(\"/api/v1/users/\", json=user_data)\n    assert response.status_code == 201\n    \n    data = response.json()\n    assert data[\"email\"] == user_data[\"email\"]\n    assert data[\"username\"] == user_data[\"username\"]\n    assert \"id\" in data\n    assert \"hashed_password\" not in data\n\ndef test_create_user_duplicate_email(client: TestClient):\n    \"\"\"Test creating user with duplicate email\"\"\"\n    user_data = {\n        \"email\": \"duplicate@example.com\",\n        \"username\": \"user1\",\n        \"password\": \"password123\"\n    }\n    \n    # Create first user\n    response1 = client.post(\"/api/v1/users/\", json=user_data)\n    assert response1.status_code == 201\n    \n    # Try to create second user with same email\n    user_data[\"username\"] = \"user2\"\n    response2 = client.post(\"/api/v1/users/\", json=user_data)\n    assert response2.status_code == 400\n    assert \"already registered\" in response2.json()[\"detail\"]\n\ndef test_get_user_unauthorized(client: TestClient):\n    \"\"\"Test accessing protected endpoint without token\"\"\"\n    response = client.get(\"/api/v1/users/me\")\n    assert response.status_code == 401\n\n@pytest.mark.asyncio\nasync def test_user_authentication_flow(client: TestClient):\n    \"\"\"Test complete authentication flow\"\"\"\n    # Create user\n    user_data = {\n        \"email\": \"auth@example.com\",\n        \"username\": \"authuser\",\n        \"password\": \"authpassword123\"\n    }\n    \n    create_response = client.post(\"/api/v1/users/\", json=user_data)\n    assert create_response.status_code == 201\n    \n    # Login\n    login_data = {\n        \"email\": user_data[\"email\"],\n        \"password\": user_data[\"password\"]\n    }\n    login_response = client.post(\"/api/v1/auth/login\", json=login_data)\n    assert login_response.status_code == 200\n    \n    token = login_response.json()[\"access_token\"]\n    \n    # Access protected endpoint\n    headers = {\"Authorization\": f\"Bearer {token}\"}\n    profile_response = client.get(\"/api/v1/users/me\", headers=headers)\n    assert profile_response.status_code == 200\n    \n    profile_data = profile_response.json()\n    assert profile_data[\"email\"] == user_data[\"email\"]\n```\n\n### 5. Deployment Configuration\n\n**Docker Configuration**\n```dockerfile\n# Dockerfile (FastAPI)\nFROM python:3.11-slim\n\nWORKDIR /app\n\n# Install system dependencies\nRUN apt-get update && apt-get install -y \\\n    gcc \\\n    && rm -rf /var/lib/apt/lists/*\n\n# Install Python dependencies\nCOPY requirements.txt .\nRUN pip install --no-cache-dir -r requirements.txt\n\n# Copy application\nCOPY . .\n\n# Create non-root user\nRUN adduser --disabled-password --gecos '' appuser\nRUN chown -R appuser:appuser /app\nUSER appuser\n\n# Health check\nHEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 \\\n    CMD curl -f http://localhost:8000/health || exit 1\n\nEXPOSE 8000\n\nCMD [\"uvicorn\", \"app.main:app\", \"--host\", \"0.0.0.0\", \"--port\", \"8000\"]\n```\n\n**Docker Compose**\n```yaml\n# docker-compose.yml\nversion: '3.8'\n\nservices:\n  api:\n    build: .\n    ports:\n      - \"8000:8000\"\n    environment:\n      - DATABASE_URL=postgresql://postgres:password@db:5432/appdb\n      - REDIS_URL=redis://redis:6379\n    depends_on:\n      - db\n      - redis\n    volumes:\n      - ./app:/app/app\n    restart: unless-stopped\n\n  db:\n    image: postgres:15\n    environment:\n      - POSTGRES_DB=appdb\n      - POSTGRES_USER=postgres\n      - POSTGRES_PASSWORD=password\n    volumes:\n      - postgres_data:/var/lib/postgresql/data\n      - ./init.sql:/docker-entrypoint-initdb.d/init.sql\n    ports:\n      - \"5432:5432\"\n    restart: unless-stopped\n\n  redis:\n    image: redis:7-alpine\n    ports:\n      - \"6379:6379\"\n    volumes:\n      - redis_data:/data\n    restart: unless-stopped\n\n  nginx:\n    image: nginx:alpine\n    ports:\n      - \"80:80\"\n      - \"443:443\"\n    volumes:\n      - ./nginx.conf:/etc/nginx/nginx.conf\n      - ./ssl:/etc/nginx/ssl\n    depends_on:\n      - api\n    restart: unless-stopped\n\nvolumes:\n  postgres_data:\n  redis_data:\n```\n\n### 6. CI/CD Pipeline\n\n**GitHub Actions Workflow**\n```yaml\n# .github/workflows/api.yml\nname: API CI/CD\n\non:\n  push:\n    branches: [main, develop]\n  pull_request:\n    branches: [main]\n\nenv:\n  REGISTRY: ghcr.io\n  IMAGE_NAME: ${{ github.repository }}\n\njobs:\n  test:\n    runs-on: ubuntu-latest\n    \n    services:\n      postgres:\n        image: postgres:15\n        env:\n          POSTGRES_PASSWORD: postgres\n          POSTGRES_DB: test_db\n        options: >-\n          --health-cmd pg_isready\n          --health-interval 10s\n          --health-timeout 5s\n          --health-retries 5\n        ports:\n          - 5432:5432\n      \n      redis:\n        image: redis:7\n        options: >-\n          --health-cmd \"redis-cli ping\"\n          --health-interval 10s\n          --health-timeout 5s\n          --health-retries 5\n        ports:\n          - 6379:6379\n\n    steps:\n    - uses: actions/checkout@v4\n    \n    - name: Set up Python\n      uses: actions/setup-python@v4\n      with:\n        python-version: '3.11'\n    \n    - name: Install dependencies\n      run: |\n        python -m pip install --upgrade pip\n        pip install -r requirements.txt\n        pip install -r requirements-dev.txt\n    \n    - name: Run linting\n      run: |\n        flake8 app tests\n        black --check app tests\n        isort --check-only app tests\n    \n    - name: Run type checking\n      run: mypy app\n    \n    - name: Run security scan\n      run: bandit -r app\n    \n    - name: Run tests\n      env:\n        DATABASE_URL: postgresql://postgres:postgres@localhost:5432/test_db\n        REDIS_URL: redis://localhost:6379\n      run: |\n        pytest tests/ -v --cov=app --cov-report=xml\n    \n    - name: Upload coverage\n      uses: codecov/codecov-action@v3\n      with:\n        file: ./coverage.xml\n\n  build:\n    needs: test\n    runs-on: ubuntu-latest\n    if: github.event_name == 'push'\n    \n    steps:\n    - uses: actions/checkout@v4\n    \n    - name: Set up Docker Buildx\n      uses: docker/setup-buildx-action@v3\n    \n    - name: Log in to Container Registry\n      uses: docker/login-action@v3\n      with:\n        registry: ${{ env.REGISTRY }}\n        username: ${{ github.actor }}\n        password: ${{ secrets.GITHUB_TOKEN }}\n    \n    - name: Extract metadata\n      id: meta\n      uses: docker/metadata-action@v5\n      with:\n        images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}\n        tags: |\n          type=ref,event=branch\n          type=ref,event=pr\n          type=sha\n    \n    - name: Build and push Docker image\n      uses: docker/build-push-action@v5\n      with:\n        context: .\n        push: true\n        tags: ${{ steps.meta.outputs.tags }}\n        labels: ${{ steps.meta.outputs.labels }}\n        cache-from: type=gha\n        cache-to: type=gha,mode=max\n\n  deploy:\n    needs: build\n    runs-on: ubuntu-latest\n    if: github.ref == 'refs/heads/main'\n    \n    steps:\n    - name: Deploy to staging\n      run: |\n        echo \"Deploying to staging environment\"\n        # Add deployment commands here\n```\n\n### 7. Monitoring and Observability\n\n**Prometheus Metrics**\n```python\n# app/core/metrics.py\nfrom prometheus_client import Counter, Histogram, Gauge, generate_latest\nfrom fastapi import Request\nimport time\n\n# Metrics\nREQUEST_COUNT = Counter(\n    'http_requests_total',\n    'Total HTTP requests',\n    ['method', 'endpoint', 'status']\n)\n\nREQUEST_DURATION = Histogram(\n    'http_request_duration_seconds',\n    'HTTP request duration',\n    ['method', 'endpoint']\n)\n\nACTIVE_CONNECTIONS = Gauge(\n    'active_connections',\n    'Active connections'\n)\n\nasync def record_metrics(request: Request, call_next):\n    \"\"\"Record metrics for each request\"\"\"\n    start_time = time.time()\n    \n    ACTIVE_CONNECTIONS.inc()\n    \n    try:\n        response = await call_next(request)\n        \n        # Record metrics\n        REQUEST_COUNT.labels(\n            method=request.method,\n            endpoint=request.url.path,\n            status=response.status_code\n        ).inc()\n        \n        REQUEST_DURATION.labels(\n            method=request.method,\n            endpoint=request.url.path\n        ).observe(time.time() - start_time)\n        \n        return response\n    \n    finally:\n        ACTIVE_CONNECTIONS.dec()\n\n@app.get(\"/metrics\")\nasync def metrics():\n    \"\"\"Prometheus metrics endpoint\"\"\"\n    return Response(\n        generate_latest(),\n        media_type=\"text/plain\"\n    )\n```\n\n## Cross-Command Integration\n\nThis command integrates seamlessly with other Claude Code commands to create complete development workflows:\n\n### 1. Complete API Development Workflow\n\n**Standard Development Pipeline:**\n```bash\n# 1. Start with API scaffold\n/api-scaffold \"User management API with FastAPI, PostgreSQL, and JWT auth\"\n\n# 2. Set up comprehensive testing\n/test-harness \"FastAPI API with unit, integration, and load testing using pytest and locust\"\n\n# 3. Security validation\n/security-scan \"FastAPI application with authentication endpoints\"\n\n# 4. Container optimization\n/docker-optimize \"FastAPI application with PostgreSQL and Redis dependencies\"\n\n# 5. Kubernetes deployment\n/k8s-manifest \"FastAPI microservice with PostgreSQL, Redis, and ingress\"\n\n# 6. Frontend integration (if needed)\n/frontend-optimize \"React application connecting to FastAPI backend\"\n```\n\n### 2. Database-First Development\n\n**When starting with existing data:**\n```bash\n# 1. Handle database migrations first\n/db-migrate \"PostgreSQL schema migration from legacy system to modern structure\"\n\n# 2. Generate API based on migrated schema\n/api-scaffold \"REST API for migrated PostgreSQL schema with auto-generated models\"\n\n# 3. Continue with standard pipeline...\n```\n\n### 3. Microservices Architecture\n\n**For distributed systems:**\n```bash\n# Generate multiple related APIs\n/api-scaffold \"User service with authentication and profile management\"\n/api-scaffold \"Order service with payment processing and inventory\"\n/api-scaffold \"Notification service with email and push notifications\"\n\n# Containerize all services\n/docker-optimize \"Microservices architecture with service discovery\"\n\n# Deploy as distributed system\n/k8s-manifest \"Microservices deployment with service mesh and monitoring\"\n```\n\n### 4. Integration with Generated Code\n\n**Test Integration Setup:**\n```yaml\n# After running /api-scaffold, use this with /test-harness\ntest_config:\n  api_base_url: \"http://localhost:8000\"\n  test_database: \"postgresql://test:test@localhost:5432/test_db\"\n  authentication:\n    test_user: \"test@example.com\"\n    test_password: \"testpassword123\"\n  \n  endpoints_to_test:\n    - POST /api/v1/users/\n    - POST /api/v1/auth/login\n    - GET /api/v1/users/me\n    - GET /api/v1/users/{id}\n```\n\n**Security Scan Configuration:**\n```yaml\n# Configuration for /security-scan after API scaffold\nsecurity_scan:\n  target: \"localhost:8000\"\n  authentication_endpoints:\n    - \"/api/v1/auth/login\"\n    - \"/api/v1/auth/refresh\"\n  protected_endpoints:\n    - \"/api/v1/users/me\"\n    - \"/api/v1/users/{id}\"\n  vulnerability_tests:\n    - jwt_token_validation\n    - sql_injection\n    - xss_prevention\n    - rate_limiting\n```\n\n**Docker Integration:**\n```dockerfile\n# Generated Dockerfile can be optimized with /docker-optimize\n# Multi-stage build for FastAPI application\nFROM python:3.11-slim as builder\nWORKDIR /app\nCOPY requirements.txt .\nRUN pip install --user -r requirements.txt\n\nFROM python:3.11-slim as runtime\nWORKDIR /app\nCOPY --from=builder /root/.local /root/.local\nCOPY . .\nENV PATH=/root/.local/bin:$PATH\nCMD [\"uvicorn\", \"app.main:app\", \"--host\", \"0.0.0.0\", \"--port\", \"8000\"]\n```\n\n**Kubernetes Deployment:**\n```yaml\n# Use this configuration with /k8s-manifest\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: api-deployment\nspec:\n  replicas: 3\n  selector:\n    matchLabels:\n      app: api\n  template:\n    metadata:\n      labels:\n        app: api\n    spec:\n      containers:\n      - name: api\n        image: api:latest\n        ports:\n        - containerPort: 8000\n        env:\n        - name: DATABASE_URL\n          valueFrom:\n            secretKeyRef:\n              name: api-secrets\n              key: database-url\n        - name: JWT_SECRET\n          valueFrom:\n            secretKeyRef:\n              name: api-secrets\n              key: jwt-secret\n        livenessProbe:\n          httpGet:\n            path: /health\n            port: 8000\n          initialDelaySeconds: 30\n          periodSeconds: 10\n        readinessProbe:\n          httpGet:\n            path: /ready\n            port: 8000\n          initialDelaySeconds: 5\n          periodSeconds: 5\n```\n\n### 5. CI/CD Pipeline Integration\n\n**Complete pipeline using multiple commands:**\n```yaml\nname: Full Stack CI/CD\n\non:\n  push:\n    branches: [main]\n\njobs:\n  api-test:\n    runs-on: ubuntu-latest\n    steps:\n    - uses: actions/checkout@v4\n    \n    # Test API (generated by /api-scaffold)\n    - name: Run API tests\n      run: |\n        # Use test configuration from /test-harness\n        pytest tests/ -v --cov=app\n    \n    # Security scan (from /security-scan)\n    - name: Security scan\n      run: |\n        bandit -r app/\n        safety check\n    \n    # Build optimized container (from /docker-optimize)\n    - name: Build container\n      run: |\n        docker build -f Dockerfile.optimized -t api:${{ github.sha }} .\n    \n    # Deploy to Kubernetes (from /k8s-manifest)\n    - name: Deploy to staging\n      run: |\n        kubectl apply -f k8s/staging/\n        kubectl set image deployment/api-deployment api=api:${{ github.sha }}\n```\n\n### 6. Frontend-Backend Integration\n\n**When building full-stack applications:**\n```bash\n# 1. Backend API\n/api-scaffold \"REST API with user management and data operations\"\n\n# 2. Frontend application\n/frontend-optimize \"React SPA with API integration, authentication, and state management\"\n\n# 3. Integration testing\n/test-harness \"End-to-end testing for React frontend and FastAPI backend\"\n\n# 4. Unified deployment\n/k8s-manifest \"Full-stack deployment with API, frontend, and database\"\n```\n\n**Frontend API Integration Code:**\n```typescript\n// Generated API client for frontend\n// Use this pattern with /frontend-optimize\nexport class APIClient {\n  private baseURL: string;\n  private token: string | null = null;\n\n  constructor(baseURL: string) {\n    this.baseURL = baseURL;\n  }\n\n  setAuthToken(token: string) {\n    this.token = token;\n  }\n\n  private async request<T>(\n    endpoint: string, \n    options: RequestInit = {}\n  ): Promise<T> {\n    const url = `${this.baseURL}${endpoint}`;\n    const headers = {\n      'Content-Type': 'application/json',\n      ...(this.token && { Authorization: `Bearer ${this.token}` }),\n      ...options.headers,\n    };\n\n    const response = await fetch(url, {\n      ...options,\n      headers,\n    });\n\n    if (!response.ok) {\n      throw new Error(`API Error: ${response.statusText}`);\n    }\n\n    return response.json();\n  }\n\n  // User management methods (matching API scaffold)\n  async createUser(userData: CreateUserRequest): Promise<User> {\n    return this.request<User>('/api/v1/users/', {\n      method: 'POST',\n      body: JSON.stringify(userData),\n    });\n  }\n\n  async login(credentials: LoginRequest): Promise<AuthResponse> {\n    return this.request<AuthResponse>('/api/v1/auth/login', {\n      method: 'POST',\n      body: JSON.stringify(credentials),\n    });\n  }\n\n  async getCurrentUser(): Promise<User> {\n    return this.request<User>('/api/v1/users/me');\n  }\n}\n```\n\n### 7. Monitoring and Observability Integration\n\n**Complete observability stack:**\n```bash\n# After API deployment, add monitoring\n/api-scaffold \"Monitoring endpoints with Prometheus metrics and health checks\"\n\n# Use with Kubernetes monitoring\n/k8s-manifest \"Kubernetes deployment with Prometheus, Grafana, and alerting\"\n```\n\nThis integrated approach ensures all components work together seamlessly, creating a production-ready system with proper testing, security, deployment, and monitoring.\n\n## Validation Checklist\n\n- [ ] Framework selected based on requirements\n- [ ] Project structure follows best practices\n- [ ] Authentication and authorization implemented\n- [ ] Input validation and sanitization in place\n- [ ] Rate limiting configured\n- [ ] Error handling comprehensive\n- [ ] Logging and monitoring setup\n- [ ] Tests written and passing\n- [ ] Security measures implemented\n- [ ] API documentation generated\n- [ ] Deployment configuration ready\n- [ ] CI/CD pipeline configured\n\nFocus on creating production-ready APIs with proper architecture, security, testing, and operational concerns addressed from the start.","contentHash":"d08373b3aee33faa4a1141495ae00e37f77955e87ef135a26f3eaf161a6acf48","copies":0,"createdAt":"2025-08-12T16:09:39.479Z","description":"Generate production-ready API endpoints with complete implementation stack","github":{"repoUrl":"https://github.com/Commands-com/commands","lastSyncDirection":"from-github","metadata":{"importedFrom":"github_repository","repoPrivate":false,"repoDefaultBranch":"main","connectedAt":"2025-08-12T16:09:39.479Z"},"importedAt":"2025-08-12T16:09:39.479Z","lastSyncAt":"2025-08-17T17:57:45.402Z","fileMapping":{"license":null,"readme":null,"assets":[],"mainFile":"tools/api-scaffold.md"},"selectedCommand":"api-scaffold","fileShas":{"mainFile":"3470b82f6bf69a0967e287c35c1d216a7d30faca","yamlPath":"313647b1fb381389da33b7913e95baf617c4b392"},"branch":"main","connectionType":"commands_yaml","connected":true,"lastSyncCommit":"01591bc061d236bde47bf23b0f47e8afcf1a5144","importSource":"repository_import","installationId":"69232615","syncStatus":"synced"},"githubRepoUrl":"https://github.com/Commands-com/commands","id":"e931b121-dee2-4b46-9eda-7e757fc05f7d","inputParameters":[{"defaultValue":"rest","name":"api_type","options":["rest","graphql","grpc","websocket","event-driven"],"description":"Type of API to scaffold","label":"API Type","type":"select","required":true},{"defaultValue":"jwt","name":"auth_method","options":["none","jwt","oauth2","api-key","basic","session","mutual-tls"],"description":"Authentication method to implement","label":"Authentication Method","type":"select","required":false},{"defaultValue":"postgresql","name":"database","options":["postgresql","mysql","mongodb","dynamodb","redis","none"],"description":"Database to use","label":"Database","type":"select","required":false},{"defaultValue":"auto-detect","name":"framework","options":["auto-detect","express","fastapi","django","spring-boot","gin","rails"],"description":"Backend framework to use","label":"Framework","type":"select","required":false}],"instructions":"Generate production-ready API endpoints with complete implementation stack","likes":0,"mcp_search_content":"","organizationUsername":"commands-com","price":"free","search_content":"api scaffold generate production-ready api endpoints with complete implementation stack /api-scaffold api-design claude-code@2025.06","title":"API Scaffold","type":"command","updatedAt":"2025-08-17T17:57:45.402Z","userId":"W0V8NAw5AhWRwcuwSoFLOi1Yem83","visibility":"public","name":"api-scaffold","userInteraction":{"userHasStarred":false}}