一键导入
tpl-backend-python-fastapi
Template do pack (backend/02-python-fastapi.md). Orienta o agente em APIs, servicos e arquitetura backend alinhado a esse contexto.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Template do pack (backend/02-python-fastapi.md). Orienta o agente em APIs, servicos e arquitetura backend alinhado a esse contexto.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
Generate custom favicons from logos, text, or brand colours. Produces favicon.svg, favicon.ico, apple-touch-icon.png, icon-192/512.png, and web manifest. Use whenever the user wants a favicon, mentions replacing a CMS default favicon, converting a logo into a favicon, creating branded initials icons, or troubleshooting favicon not displaying / iOS black square / missing manifest.
"Get a second opinion from leading AI models on code, architecture, strategy, prompting, or anything. Queries models via OpenRouter, Gemini, or OpenAI APIs. Supports single opinion, multi-model consensus, and devil's advocate patterns. Use whenever the user says 'brains trust', 'second opinion', 'ask gemini', 'ask gpt', 'peer review', 'consult another model', 'challenge this', or 'devil's advocate'."
Run an independent code review using the OpenAI Codex CLI in headless mode. Gets a second opinion from a different model family (GPT-5/o3) on recent changes, a PR, a commit, or the whole app — covering bugs, regressions, security, data consistency, UX/state bugs, performance risks, and testing gaps. Saves a severity-prioritised report to .jez/reviews/. Triggers: 'codex review', 'review with codex', 'second opinion on this code', 'independent code review', 'what does codex think', 'get codex to review'.
Deep research and discovery before building something new. Explores local projects for reusable code, researches competitors, reads forums and reviews, analyses plugin ecosystems, investigates technical options, and produces a comprehensive research brief. Three depths: focused (30 min), wide (1-2 hours), deep (3-6 hours). Triggers: 'research this', 'deep research', 'discovery', 'explore the space', 'what should I build', 'competitive analysis', 'before I start building', 'research before coding'.
Plan and execute entire application builds. Generates phased delivery roadmaps, then executes them autonomously — phase by phase, committing at milestones, deploying, testing, and continuing until done or stuck. Modes: plan (generate roadmap), start (begin executing), resume (continue from where you left off), status (show progress). Triggers: 'roadmap', 'plan the build', 'start building', 'resume the build', 'keep going', 'build the whole thing', 'execute the roadmap', 'what phase are we on'.
Walk through a live web app AS a real user to find usability + behavioural bugs that static reviews miss. REQUIRES proof of interaction (typing, clicking, sending, observing) before any verdict — a sweep that didn't interact terminates with verdict 'Incomplete'. Walks threads, exercises every element, runs the multi-pane stress matrix, visual polish sweep, component perfection checklist, automated a11y (axe-core), pragmatic performance budget (LCP/CLS/INP), scenario battery (11 scenarios), and stress recipes including the real-flavour data battery. Hard gates: console errors/warnings = 0, network 5xx = 0, layout collapse = 0, axe Critical/Serious = 0, perf budget green. Audit-the-audit meta-check rejects rushed reports. Each finding has reproduction steps, evidence path, and suspected code location. Trigger with 'ux audit', 'walkthrough', 'qa sweep', 'audit the app', 'dogfood this', 'check all pages', 'find what's broken', 'stress the UI'.
| name | tpl-backend-python-fastapi |
| description | Template do pack (backend/02-python-fastapi.md). Orienta o agente em APIs, servicos e arquitetura backend alinhado a esse contexto. |
| metadata | {"version":"1.0.0","source_template":"backend/02-python-fastapi.md","generated_by":"install_pack_templates_as_claude_skills"} |
Skill gerado a partir do pack templates-claude-code. Arquivo de origem: backend/02-python-fastapi.md. Use como baseline e adapte ao projeto antes de mudancas grandes.
| Technology | Version | Purpose |
|---|---|---|
| Python | 3.12 | Runtime |
| FastAPI | 0.111+ | HTTP framework |
| SQLAlchemy | 2.0 async | ORM |
| asyncpg | 0.29+ | Async PostgreSQL driver |
| Alembic | 1.13+ | Database migrations |
| Pydantic | v2 | Request/response validation + settings |
| pytest | 8.x | Test runner |
| httpx | 0.27+ | Async HTTP client for tests |
| ruff | 0.4+ | Linting + formatting |
| mypy | 1.10+ | Static type checking |
| python-jose | 3.x | JWT tokens |
| passlib[bcrypt] | 1.7+ | Password hashing |
app/
├── core/
│ ├── config.py # Pydantic BaseSettings — env vars
│ ├── security.py # JWT creation/verification, password hashing
│ ├── database.py # Async engine + session factory
│ └── exceptions.py # Custom HTTP exceptions + handlers
├── modules/
│ └── users/
│ ├── router.py # APIRouter, endpoints only
│ ├── service.py # Business logic
│ ├── repository.py # DB queries (SQLAlchemy)
│ ├── models.py # SQLAlchemy ORM models
│ ├── schemas.py # Pydantic request/response schemas
│ └── dependencies.py # FastAPI Depends() factories
├── middlewares/
│ ├── logging.py # Request/response logging
│ └── cors.py # CORS config
├── tasks/
│ └── email.py # Background tasks (send email, etc.)
├── migrations/
│ ├── env.py # Alembic async env config
│ └── versions/ # Auto-generated migration files
└── main.py # App factory, include_router, lifespan
alembic.ini
pyproject.toml
tests/
├── conftest.py # Fixtures: async client, test DB, test user
├── unit/
│ └── users/
│ └── test_service.py
└── integration/
└── users/
└── test_router.py
Request or Responseif/else logicasync def; synchronous endpoints use run_in_executormodel_config = ConfigDict(from_attributes=True) for ORM conversion# app/core/database.py
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from app.core.config import settings
engine = create_async_engine(
settings.DATABASE_URL,
pool_size=10,
max_overflow=20,
echo=settings.DEBUG,
)
AsyncSessionLocal = async_sessionmaker(
engine,
expire_on_commit=False,
class_=AsyncSession,
)
async def get_db() -> AsyncGenerator[AsyncSession, None]:
async with AsyncSessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
# app/modules/users/dependencies.py
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db
from app.core.security import decode_access_token
from app.modules.users.repository import UserRepository
from app.modules.users.models import User
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")
async def get_current_user(
token: str = Depends(oauth2_scheme),
db: AsyncSession = Depends(get_db),
) -> User:
payload = decode_access_token(token) # raises 401 if invalid
user = await UserRepository(db).get_by_id(payload["sub"])
if not user:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
return user
async def require_admin(
current_user: User = Depends(get_current_user),
) -> User:
if current_user.role != "admin":
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin required")
return current_user
# app/modules/auth/router.py
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db
from app.core.security import verify_password, create_access_token, create_refresh_token
from app.modules.users.repository import UserRepository
router = APIRouter(prefix="/auth", tags=["auth"])
@router.post("/login")
async def login(
form_data: OAuth2PasswordRequestForm = Depends(),
db: AsyncSession = Depends(get_db),
):
repo = UserRepository(db)
user = await repo.get_by_email(form_data.username)
if not user or not verify_password(form_data.password, user.hashed_password):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid credentials",
)
return {
"access_token": create_access_token({"sub": str(user.id), "role": user.role}),
"refresh_token": create_refresh_token(str(user.id)),
"token_type": "bearer",
}
# app/tasks/email.py
from fastapi import BackgroundTasks
import smtplib
from app.core.config import settings
def send_welcome_email(email: str, name: str) -> None:
# This runs in a thread pool — do NOT use async here
print(f"Sending welcome email to {email}")
# In router:
@router.post("/register", status_code=201)
async def register(
body: UserCreateSchema,
db: AsyncSession = Depends(get_db),
background_tasks: BackgroundTasks = BackgroundTasks(),
):
user = await UserService(db).create(body)
background_tasks.add_task(send_welcome_email, user.email, user.name)
return user
# app/core/config.py
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8")
DATABASE_URL: str
SECRET_KEY: str
ALGORITHM: str = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES: int = 15
REFRESH_TOKEN_EXPIRE_DAYS: int = 7
DEBUG: bool = False
CORS_ORIGINS: list[str] = ["http://localhost:5173"]
settings = Settings()
| Trigger | Method | Route | Auth | Handler |
|---|---|---|---|---|
| Register | POST | /api/v1/auth/register | Public | auth.register |
| Login | POST | /api/v1/auth/login | Public (form) | auth.login |
| Refresh | POST | /api/v1/auth/refresh | Refresh token | auth.refresh |
| Get profile | GET | /api/v1/users/me | Bearer | users.me |
| Update profile | PATCH | /api/v1/users/me | Bearer | users.update_me |
| List all users | GET | /api/v1/users | Bearer + admin | users.list |
| Get user by ID | GET | /api/v1/users/{id} | Bearer + admin | users.get |
| Delete user | DELETE | /api/v1/users/{id} | Bearer + admin | users.delete |
| Health check | GET | /health | Public | health.check |
Before opening a PR, verify ALL of the following:
ruff check . && ruff format --check . passes with zero issuesmypy app/ passes — no type: ignore without a comment explaining whypytest -x --tb=short passes with zero failuresalembic revision --autogeneratealembic upgrade head && alembic downgrade -1async def functions — always awaitSettingssession.execute(text("raw SQL")) — use SQLAlchemy ORM expressionsasync def route handlers that block on sync I/O without run_in_executorAsyncSession across multiple requestsfrom __future__ import annotations — it breaks Pydantic v2 at runtime.env (gitignored) and .env.exampleUnion[X, None] — use X | None (Python 3.10+ syntax)global variables for shared state — use dependency injection# type: ignore — fix the types