All skills
jeffallan avatar

/fastapi-expert

@efebc44
by jeffallanjeffallan/claude-skills12k stars
1,127

Use 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 OpenAPI documentation. Trigger terms: FastAPI, Pydantic, async Python, Python API, REST API Python, SQLAlchemy async, JWT authentication, OpenAPI, Swagger Python.

Use this Skill: https://skilld.dev/gh/jeffallan/claude-skills/fastapi-expert

This session only. Nothing lands on disk.

referencesauthentication.md

≈1.1k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Authentication

OAuth2 Password Flow

from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from typing import Annotated

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/token")

@router.post("/token")
async def login(
    db: DB,
    form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
) -> Token:
    user = await authenticate_user(db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status.HTTP_401_UNAUTHORIZED,
            "Incorrect email or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return Token(
        access_token=create_access_token(sub=str(user.id)),
        token_type="bearer",
    )

JWT Token Creation

from datetime import datetime, timedelta, UTC
from jose import JWTError, jwt
from passlib.context import CryptContext

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def verify_password(plain: str, hashed: str) -> bool:
    return pwd_context.verify(plain, hashed)

def hash_password(password: str) -> str:
    return pwd_context.hash(password)

def create_access_token(
    sub: str,
    expires_delta: timedelta | None = None,
) -> str:
    expire = datetime.now(UTC) + (expires_delta or timedelta(minutes=15))
    return jwt.encode(
        {"sub": sub, "exp": expire, "type": "access"},
        settings.SECRET_KEY,
        algorithm="HS256",
    )

def create_refresh_token(sub: str) -> str:
    expire = datetime.now(UTC) + timedelta(days=7)
    return jwt.encode(
        {"sub": sub, "exp": expire, "type": "refresh"},
        settings.SECRET_KEY,
        algorithm="HS256",
    )

Get Current User

async def get_current_user(
    db: DB,
    token: Annotated[str, Depends(oauth2_scheme)],
) -> User:
    credentials_exception = HTTPException(
        status.HTTP_401_UNAUTHORIZED,
        "Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
        user_id = int(payload.get("sub"))
        if payload.get("type") != "access":
            raise credentials_exception
    except (JWTError, ValueError, TypeError):
        raise credentials_exception

    user = await get_user_db(db, user_id)
    if not user:
        raise credentials_exception
    return user

CurrentUser = Annotated[User, Depends(get_current_user)]

Role-Based Access

from enum import Enum

class UserRole(str, Enum):
    USER = "user"
    ADMIN = "admin"
    MODERATOR = "moderator"

def require_roles(*roles: UserRole):
    async def role_checker(current_user: CurrentUser) -> User:
        if current_user.role not in roles:
            raise HTTPException(
                status.HTTP_403_FORBIDDEN,
                f"Required roles: {[r.value for r in roles]}",
            )
        return current_user
    return role_checker

# Usage
@router.delete("/{id}")
async def delete_user(
    user_id: int,
    admin: Annotated[User, Depends(require_roles(UserRole.ADMIN))],
) -> None:
    ...

Refresh Token

@router.post("/refresh", response_model=Token)
async def refresh_token(
    db: DB,
    refresh_token: str = Body(..., embed=True),
) -> Token:
    try:
        payload = jwt.decode(refresh_token, settings.SECRET_KEY, algorithms=["HS256"])
        if payload.get("type") != "refresh":
            raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid token type")
        user_id = int(payload.get("sub"))
    except (JWTError, ValueError):
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid refresh token")

    user = await get_user_db(db, user_id)
    if not user:
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, "User not found")

    return Token(
        access_token=create_access_token(sub=str(user.id)),
        token_type="bearer",
    )

Quick Reference

Component Purpose
OAuth2PasswordBearer Extract token from header
OAuth2PasswordRequestForm Login form data
jwt.encode() Create JWT
jwt.decode() Verify JWT
pwd_context.hash() Hash password
pwd_context.verify() Check password
Depends(get_current_user) Require auth
require_roles() Role-based access

Source: SKILL.md on GitHub

1 alert16d5 checks · Risk CRITICAL
  • Gen Agent Trust Hub16d

    The skill is an educational reference guide for FastAPI development and contains no malicious patterns or security risks. The automated alerts regarding the documentation URL are false positives, as the link belongs to the author's official GitHub pages deployment and contains standard project references.

  • Socket16d

    No alerts

  • Snyk16d

    Risk: LOW · No issues

  • Runlayer6mo

    1/7 files flagged

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at efebc44. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 2 months ago.

Steadyupdated 5 months ago
Other metadata
metadata
{
  "author": "https://github.com/Jeffallan",
  "version": "1.1.0",
  "domain": "backend",
  "triggers": "FastAPI, Pydantic, async Python, Python API, REST API Python, SQLAlchemy async, JWT authentication, OpenAPI, Swagger Python",
  "role": "specialist",
  "scope": "implementation",
  "output-format": "code",
  "related-skills": "fullstack-guardian, django-expert, test-master"
}
  • Python
  • fastapi
  • pydantic
  • async
  • rest-api
  • sqlalchemy
  • jwt
  • websockets
  • openapi

README badge

README badge for jeffallan/claude-skills/fastapi-expert

Implements async REST APIs, Pydantic V2 schemas, SQLAlchemy database operations, and JWT authentication with FastAPI. Covers endpoint design, dependency injection, validation, async CRUD workflows, and OpenAPI documentation generation.

Generated from the current SKILL.md.

Does this skill work with Pydantic V1?
No. The skill is built for Pydantic V2 syntax only (field_validator, model_validator, model_config). It does not support Pydantic V1 decorators like @validator.
Can I use this skill with synchronous database operations?
No. The skill assumes async/await for all I/O operations and relies on SQLAlchemy async. Mixing sync and async code improperly is explicitly forbidden.
Does this skill cover WebSocket endpoints?
Yes. WebSocket endpoint creation is listed as a core use case, though the SKILL.md does not include a detailed example.
What testing approach does this skill recommend?
The skill recommends pytest with pytest-asyncio and httpx for async testing, with OpenAPI docs verification at /docs as a checkpoint.
Does this skill include database migration tooling?
The skill covers async SQLAlchemy models and references Alembic migrations, but focuses on ORM and CRUD operations rather than migration generation.

Generated from the current SKILL.md. These answers refresh after source changes.