$npx -y skills add Jeffallan/claude-skills --skill fastapi-expertUse when building high-performance async Python APIs with FastAPI and Pydantic V2. Invoke to create REST endpoints, define Pydantic models, implement authentication flows, set up async SQLAlchemy database operations, add JWT authentication, build WebSocket endpoints, or generate
| 1 | # FastAPI Expert |
| 2 | |
| 3 | Deep expertise in async Python, Pydantic V2, and production-grade API development with FastAPI. |
| 4 | |
| 5 | ## When to Use This Skill |
| 6 | |
| 7 | - Building REST APIs with FastAPI |
| 8 | - Implementing Pydantic V2 validation schemas |
| 9 | - Setting up async database operations |
| 10 | - Implementing JWT authentication/authorization |
| 11 | - Creating WebSocket endpoints |
| 12 | - Optimizing API performance |
| 13 | |
| 14 | ## Core Workflow |
| 15 | |
| 16 | 1. **Analyze requirements** — Identify endpoints, data models, auth needs |
| 17 | 2. **Design schemas** — Create Pydantic V2 models for validation |
| 18 | 3. **Implement** — Write async endpoints with proper dependency injection |
| 19 | 4. **Secure** — Add authentication, authorization, rate limiting |
| 20 | 5. **Test** — Write async tests with pytest and httpx; run `pytest` after each endpoint group and verify OpenAPI docs at `/docs` |
| 21 | |
| 22 | > **Checkpoint after each step:** confirm schemas validate correctly, endpoints return expected HTTP status codes, and `/docs` reflects the intended API surface before proceeding. |
| 23 | |
| 24 | ## Minimal Complete Example |
| 25 | |
| 26 | Schema + endpoint + dependency injection in one cohesive unit: |
| 27 | |
| 28 | ```python |
| 29 | # schemas.py |
| 30 | from pydantic import BaseModel, EmailStr, field_validator, model_config |
| 31 | |
| 32 | class UserCreate(BaseModel): |
| 33 | model_config = model_config(str_strip_whitespace=True) |
| 34 | |
| 35 | email: EmailStr |
| 36 | password: str |
| 37 | name: str | None = None |
| 38 | |
| 39 | @field_validator("password") |
| 40 | @classmethod |
| 41 | def password_strength(cls, v: str) -> str: |
| 42 | if len(v) < 8: |
| 43 | raise ValueError("Password must be at least 8 characters") |
| 44 | return v |
| 45 | |
| 46 | class UserResponse(BaseModel): |
| 47 | model_config = model_config(from_attributes=True) |
| 48 | |
| 49 | id: int |
| 50 | email: EmailStr |
| 51 | name: str | None = None |
| 52 | ``` |
| 53 | |
| 54 | ```python |
| 55 | # routers/users.py |
| 56 | from fastapi import APIRouter, Depends, HTTPException, status |
| 57 | from sqlalchemy.ext.asyncio import AsyncSession |
| 58 | from typing import Annotated |
| 59 | |
| 60 | from app.database import get_db |
| 61 | from app.schemas import UserCreate, UserResponse |
| 62 | from app import crud |
| 63 | |
| 64 | router = APIRouter(prefix="/users", tags=["users"]) |
| 65 | |
| 66 | DbDep = Annotated[AsyncSession, Depends(get_db)] |
| 67 | |
| 68 | @router.post("/", response_model=UserResponse, status_code=status.HTTP_201_CREATED) |
| 69 | async def create_user(payload: UserCreate, db: DbDep) -> UserResponse: |
| 70 | existing = await crud.get_user_by_email(db, payload.email) |
| 71 | if existing: |
| 72 | raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Email already registered") |
| 73 | return await crud.create_user(db, payload) |
| 74 | ``` |
| 75 | |
| 76 | ```python |
| 77 | # crud.py |
| 78 | from sqlalchemy import select |
| 79 | from sqlalchemy.ext.asyncio import AsyncSession |
| 80 | from app.models import User |
| 81 | from app.schemas import UserCreate |
| 82 | from app.security import hash_password |
| 83 | |
| 84 | async def get_user_by_email(db: AsyncSession, email: str) -> User | None: |
| 85 | result = await db.execute(select(User).where(User.email == email)) |
| 86 | return result.scalar_one_or_none() |
| 87 | |
| 88 | async def create_user(db: AsyncSession, payload: UserCreate) -> User: |
| 89 | user = User(email=payload.email, hashed_password=hash_password(payload.password), name=payload.name) |
| 90 | db.add(user) |
| 91 | await db.commit() |
| 92 | await db.refresh(user) |
| 93 | return user |
| 94 | ``` |
| 95 | |
| 96 | ## JWT Authentication Snippet |
| 97 | |
| 98 | ```python |
| 99 | # security.py |
| 100 | from datetime import datetime, timedelta, timezone |
| 101 | from jose import JWTError, jwt |
| 102 | from fastapi import Depends, HTTPException, status |
| 103 | from fastapi.security import OAuth2PasswordBearer |
| 104 | from typing import Annotated |
| 105 | |
| 106 | SECRET_KEY = "read-from-env" # use os.environ / settings |
| 107 | ALGORITHM = "HS256" |
| 108 | oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/token") |
| 109 | |
| 110 | def create_access_token(subject: str, expires_delta: timedelta = timedelta(minutes=30)) -> str: |
| 111 | payload = {"sub": subject, "exp": datetime.now(timezone.utc) + expires_delta} |
| 112 | return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM) |
| 113 | |
| 114 | async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]) -> str: |
| 115 | try: |
| 116 | data = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) |
| 117 | subject: str | None = data.get("sub") |
| 118 | if subject is None: |
| 119 | raise ValueError |
| 120 | return subject |
| 121 | except (JWTError, ValueError): |
| 122 | raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Inva |