All skills
jeffallan avatar

/fastapi-expert

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

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.

referencesendpoints-routing.md

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

Endpoints & Routing

Router Setup

from fastapi import APIRouter, Depends, HTTPException, status, Query, Path
from typing import Annotated

router = APIRouter(prefix="/users", tags=["users"])

# Type aliases for common dependencies
DB = Annotated[AsyncSession, Depends(get_db)]
CurrentUser = Annotated[User, Depends(get_current_user)]
Pagination = Annotated[int, Query(ge=1, le=100)]

CRUD Endpoints

@router.post("/", response_model=UserOut, status_code=status.HTTP_201_CREATED)
async def create_user(db: DB, user_in: UserCreate) -> User:
    if await get_user_by_email(db, user_in.email):
        raise HTTPException(status.HTTP_400_BAD_REQUEST, "Email already registered")
    return await create_user_db(db, user_in)

@router.get("/", response_model=list[UserOut])
async def list_users(
    db: DB,
    current_user: CurrentUser,
    skip: int = Query(0, ge=0),
    limit: Pagination = 20,
) -> list[User]:
    return await get_users(db, skip=skip, limit=limit)

@router.get("/{user_id}", response_model=UserOut)
async def get_user(
    db: DB,
    user_id: Annotated[int, Path(gt=0)],
) -> User:
    user = await get_user_db(db, user_id)
    if not user:
        raise HTTPException(status.HTTP_404_NOT_FOUND, "User not found")
    return user

@router.patch("/{user_id}", response_model=UserOut)
async def update_user(
    db: DB,
    user_id: int,
    user_in: UserUpdate,
    current_user: CurrentUser,
) -> User:
    if current_user.id != user_id and not current_user.is_admin:
        raise HTTPException(status.HTTP_403_FORBIDDEN, "Not authorized")
    return await update_user_db(db, user_id, user_in)

@router.delete("/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_user(db: DB, user_id: int, current_user: CurrentUser) -> None:
    if not await delete_user_db(db, user_id):
        raise HTTPException(status.HTTP_404_NOT_FOUND, "User not found")

Custom Dependencies

from fastapi import Depends

async def get_current_active_user(
    current_user: CurrentUser,
) -> User:
    if not current_user.is_active:
        raise HTTPException(status.HTTP_400_BAD_REQUEST, "Inactive user")
    return current_user

ActiveUser = Annotated[User, Depends(get_current_active_user)]

async def require_admin(current_user: CurrentUser) -> User:
    if not current_user.is_admin:
        raise HTTPException(status.HTTP_403_FORBIDDEN, "Admin required")
    return current_user

AdminUser = Annotated[User, Depends(require_admin)]

Query Parameters

@router.get("/search")
async def search_users(
    db: DB,
    q: str = Query(min_length=1, max_length=100),
    is_active: bool | None = None,
    role: UserRole | None = None,
    created_after: datetime | None = None,
    sort_by: Annotated[str, Query(pattern="^(name|email|created_at)$")] = "created_at",
    order: Annotated[str, Query(pattern="^(asc|desc)$")] = "desc",
) -> list[User]:
    return await search_users_db(db, q, is_active, role, created_after, sort_by, order)

Include Router

# main.py
from fastapi import FastAPI
from app.api.v1 import users, auth, posts

app = FastAPI()

app.include_router(users.router, prefix="/api/v1")
app.include_router(auth.router, prefix="/api/v1")
app.include_router(posts.router, prefix="/api/v1")

Response Models

from fastapi import Response

@router.get("/", response_model=list[UserOut], response_model_exclude_unset=True)
async def list_users(...) -> list[User]:
    ...

@router.get("/{id}", responses={
    200: {"model": UserOut},
    404: {"description": "User not found"},
})
async def get_user(...) -> User:
    ...

Quick Reference

Decorator Purpose
@router.get("/") GET endpoint
@router.post("/", status_code=201) POST with status
Query(ge=0) Query param validation
Path(gt=0) Path param validation
Depends(func) Dependency injection
Annotated[T, Depends()] Type alias pattern
response_model=Model Response schema
HTTPException(status, detail) Error response

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.