From python-fastapi-scaffold-plugin
Scaffolds modern Python FastAPI projects with UV package management, Docker support, K8s/Cloud Run deployment templates, testing setup, and best practices. Use when starting a new Python web service, API, or microservice project. Includes complete project structure, configuration management with Pydantic, containerization, and CI/CD patterns.
npx claudepluginhub darkflib/skill-marketplace --plugin python-fastapi-scaffold-pluginThis skill uses the workspace's default tool permissions.
Provides automated scaffolding for production-ready Python FastAPI projects following modern best practices. Creates a complete project structure with UV for package management, Docker containerization, Kubernetes deployment templates, testing infrastructure, and development tooling.
assets/Dockerfileassets/README.mdassets/app/__init__.pyassets/app/api/__init__.pyassets/app/api/routes.pyassets/app/core/__init__.pyassets/app/core/config.pyassets/app/main.pyassets/app/models/__init__.pyassets/app/services/__init__.pyassets/deploy/k8s/deployment.yamlassets/deploy/k8s/service.yamlassets/docker-compose.ymlassets/pyproject.tomlassets/tests/__init__.pyassets/tests/conftest.pyscripts/scaffold.pyGuides Next.js Cache Components and Partial Prerendering (PPR) with cacheComponents enabled. Implements 'use cache', cacheLife(), cacheTag(), revalidateTag(), static/dynamic optimization, and cache debugging.
Migrates code, prompts, and API calls from Claude Sonnet 4.0/4.5 or Opus 4.1 to Opus 4.5, updating model strings on Anthropic, AWS, GCP, Azure platforms.
Automates semantic versioning and release workflow for Claude Code plugins: bumps versions in package.json, marketplace.json, plugin.json; verifies builds; creates git tags, GitHub releases, changelogs.
Provides automated scaffolding for production-ready Python FastAPI projects following modern best practices. Creates a complete project structure with UV for package management, Docker containerization, Kubernetes deployment templates, testing infrastructure, and development tooling.
Use this skill when:
The fastest way to create a new project:
# Navigate to where you want to create the project
cd /workspace
# Run the scaffold script
python /mnt/skills/[skill-path]/scripts/scaffold.py my-project "My API description"
This creates a complete project structure ready for development.
If you prefer to create the structure manually or customize the scaffolding:
/mnt/skills/[skill-path]/assets/{{PROJECT_NAME}} → your project name{{DESCRIPTION}} → your project descriptionThe scaffold creates the following structure:
my-project/
├── app/
│ ├── __init__.py
│ ├── main.py # FastAPI application entry point
│ ├── api/
│ │ ├── __init__.py
│ │ └── routes.py # API route definitions
│ ├── core/
│ │ ├── __init__.py
│ │ └── config.py # Pydantic settings
│ ├── models/ # Pydantic models
│ │ └── __init__.py
│ └── services/ # Business logic
│ └── __init__.py
├── tests/
│ ├── __init__.py
│ ├── conftest.py # Pytest fixtures
│ ├── unit/
│ └── integration/
├── deploy/
│ └── k8s/
│ ├── deployment.yaml # Kubernetes deployment
│ └── service.yaml # Kubernetes service
├── scripts/ # Utility scripts
├── pyproject.toml # UV project configuration
├── Dockerfile # Multi-stage production build
├── docker-compose.yml # Local development environment
├── .env.example # Environment variable template
├── .gitignore
└── README.md
The scaffold uses Pydantic Settings for type-safe configuration:
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
APP_NAME: str = "my-project"
DEBUG: bool = False
DATABASE_URL: PostgresDsn
REDIS_URL: RedisDsn
SECRET_KEY: str
model_config = SettingsConfigDict(
env_file=".env",
case_sensitive=False,
)
settings = get_settings() # Cached singleton
Benefits:
The .env.example file provides a template:
# Application
APP_NAME=my-project
DEBUG=false
LOG_LEVEL=INFO
# Database
DATABASE_URL=postgresql://user:pass@postgres:5432/db
# Redis
REDIS_URL=redis://redis:6379
# Security
SECRET_KEY=change-in-production
CORS_ORIGINS=http://localhost:3000
# Install dependencies
uv sync
# Copy environment template
cp .env.example .env
# Edit .env with your configuration
nano .env
# Run development server with auto-reload
uv run uvicorn app.main:app --reload
# Access the API
# http://localhost:8000 - API
# http://localhost:8000/docs - Swagger UI
# http://localhost:8000/health - Health check
# Start all services (app, postgres, redis)
docker-compose up -d
# View logs
docker-compose logs -f app
# Stop services
docker-compose down
# Rebuild after code changes
docker-compose up -d --build app
# All tests
uv run pytest
# With coverage
uv run pytest --cov=app --cov-report=html
# Specific test file
uv run pytest tests/unit/test_routes.py
# Watch mode (requires pytest-watch)
uv run ptw
# Lint code
uv run ruff check .
# Format code
uv run ruff format .
# Type checking
uv run mypy app/
# All checks (add to CI)
uv run ruff check . && \
uv run ruff format --check . && \
uv run mypy app/ && \
uv run pytest --cov=app
# Add production dependency
uv add fastapi-cache2
# Add development dependency
uv add --dev pytest-mock
# Update all dependencies
uv sync --upgrade
# Lock without installing
uv lock
The scaffold includes an optimized multi-stage Dockerfile:
Builder stage:
--no-dev)Production stage:
# Build for local testing
docker build -t my-project:latest .
# Build for specific platform
docker build --platform linux/amd64 -t my-project:latest .
# Build and tag for registry
docker build -t gcr.io/project/my-project:v1.0.0 .
The included docker-compose.yml provides:
The scaffold includes production-ready K8s manifests:
Deployment features:
Applying manifests:
# Create secrets first
kubectl create secret generic my-project-secrets \
--from-literal=database-url='postgresql://...' \
--from-literal=redis-url='redis://...' \
--from-literal=secret-key='...'
# Apply deployment and service
kubectl apply -f deploy/k8s/
# Check status
kubectl get deployments
kubectl get pods
kubectl get services
kubectl logs -l app=my-project
The Dockerfile is compatible with Cloud Run:
# Build and push to GCR
gcloud builds submit --tag gcr.io/PROJECT_ID/my-project
# Deploy to Cloud Run
gcloud run deploy my-project \
--image gcr.io/PROJECT_ID/my-project \
--platform managed \
--region us-central1 \
--set-env-vars="DATABASE_URL=postgresql://...,SECRET_KEY=..." \
--allow-unauthenticated
# With secrets from Secret Manager
gcloud run deploy my-project \
--image gcr.io/PROJECT_ID/my-project \
--platform managed \
--set-secrets="DATABASE_URL=db-url:latest,SECRET_KEY=secret-key:latest"
Create models in app/models/:
# app/models/user.py
from pydantic import BaseModel, EmailStr
class User(BaseModel):
id: int
email: EmailStr
full_name: str | None = None
Create routers in app/api/:
# app/api/users.py
from fastapi import APIRouter
router = APIRouter(prefix="/users", tags=["users"])
@router.get("/")
async def list_users():
return []
Include in app/main.py:
from app.api.users import router as users_router
app.include_router(users_router)
Create business logic in app/services/:
# app/services/email.py
class EmailService:
async def send_email(self, to: str, subject: str, body: str):
# Email sending logic
pass
For database connections, external APIs, etc.:
# app/core/database.py
from sqlalchemy.ext.asyncio import create_async_engine
engine = create_async_engine(settings.DATABASE_URL)
async def get_db():
async with AsyncSession(engine) as session:
yield session
Use in routes:
from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession
@router.get("/items")
async def list_items(db: AsyncSession = Depends(get_db)):
# Use db session
pass
If you don't need these services:
docker-compose.ymlpyproject.toml dependencies.env.example to remove DB/Redis varsapp/core/config.py settingsFor job queues, schedulers, workers:
uv add celery or uv add arqapp/workers/ directorydocker-compose.yml with worker serviceFor JWT, OAuth2, etc.:
uv add python-jose[cryptography] passlib[bcrypt]app/core/security.py for auth logicFastAPI's dependency injection for reusable components:
from fastapi import Depends
async def get_current_user(token: str = Depends(oauth2_scheme)):
# Verify token and return user
return user
@router.get("/me")
async def read_users_me(current_user: User = Depends(get_current_user)):
return current_user
For tasks that don't need immediate execution:
from fastapi import BackgroundTasks
def send_email(email: str, message: str):
# Send email
pass
@router.post("/send")
async def send_notification(
email: str,
background_tasks: BackgroundTasks
):
background_tasks.add_task(send_email, email, "notification")
return {"message": "Email will be sent"}
For request/response processing:
from fastapi import Request
import time
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
Custom exception handlers:
from fastapi import HTTPException, Request
from fastapi.responses import JSONResponse
@app.exception_handler(ValueError)
async def value_error_handler(request: Request, exc: ValueError):
return JSONResponse(
status_code=400,
content={"message": str(exc)},
)
# Clear cache and retry
uv cache clean
uv sync
# Find process using port 8000
lsof -ti:8000 | xargs kill -9
# Or use different port
uv run uvicorn app.main:app --port 8001
# Check Docker is running
docker ps
# Clean build cache
docker builder prune
# Build with verbose output
docker build --progress=plain -t my-project .
# Run with verbose output
uv run pytest -vv
# Run specific test
uv run pytest tests/unit/test_routes.py::test_get_item -vv
# Debug with pdb
uv run pytest --pdb
If converting an existing project to UV:
# Import from requirements.txt
uv add -r requirements.txt
# Or let UV detect dependencies
uv init
# Verify pyproject.toml
cat pyproject.toml
This scaffold provides:
Use the scaffold script for instant project setup, then customize based on your specific requirements.