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.

referencespydantic-v2.md

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

Pydantic V2 Schemas

Schema Patterns

from pydantic import BaseModel, EmailStr, Field, field_validator, model_validator
from typing import Self

class UserCreate(BaseModel):
    email: EmailStr
    password: str = Field(min_length=8)
    username: str = Field(min_length=3, max_length=50)
    age: int = Field(ge=18, le=120)

    @field_validator('password')
    @classmethod
    def validate_password(cls, v: str) -> str:
        if not any(c.isupper() for c in v):
            raise ValueError('Password must contain uppercase')
        if not any(c.isdigit() for c in v):
            raise ValueError('Password must contain digit')
        return v

    @field_validator('username')
    @classmethod
    def validate_username(cls, v: str) -> str:
        if not v.isalnum():
            raise ValueError('Username must be alphanumeric')
        return v.lower()

class UserUpdate(BaseModel):
    email: EmailStr | None = None
    username: str | None = Field(None, min_length=3, max_length=50)

ORM Mode (from_attributes)

class UserResponse(BaseModel):
    model_config = {"from_attributes": True}

    id: int
    email: EmailStr
    username: str
    is_active: bool = True
    created_at: datetime

# Usage with SQLAlchemy model
user_response = UserResponse.model_validate(db_user)

Model Validator

class OrderCreate(BaseModel):
    items: list[OrderItem]
    discount_code: str | None = None
    total: float

    @model_validator(mode='after')
    def validate_order(self) -> Self:
        calculated = sum(item.price * item.quantity for item in self.items)
        if abs(self.total - calculated) > 0.01:
            raise ValueError('Total does not match items')
        return self

Nested Models

class Address(BaseModel):
    street: str
    city: str
    country: str = Field(default="US")

class UserWithAddress(BaseModel):
    name: str
    addresses: list[Address] = Field(default_factory=list)

Serialization Control

class User(BaseModel):
    model_config = {
        "from_attributes": True,
        "json_schema_extra": {
            "example": {"email": "user@example.com", "username": "johndoe"}
        }
    }

    id: int
    email: EmailStr
    password: str = Field(exclude=True)  # Never serialize
    internal_id: str = Field(repr=False)  # Hide from repr

# Serialize with aliases
class ApiResponse(BaseModel):
    model_config = {"populate_by_name": True}

    user_id: int = Field(alias="userId", serialization_alias="user_id")

Settings (Pydantic V2)

from pydantic_settings import BaseSettings, SettingsConfigDict

class Settings(BaseSettings):
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=True,
    )

    DATABASE_URL: str
    SECRET_KEY: str
    DEBUG: bool = False
    CORS_ORIGINS: list[str] = ["http://localhost:3000"]
    API_V1_PREFIX: str = "/api/v1"

settings = Settings()

Quick Reference

V1 Syntax V2 Syntax
@validator @field_validator
@root_validator @model_validator
class Config model_config = {}
orm_mode = True from_attributes = True
Optional[X] X | None
.dict() .model_dump()
.parse_obj() .model_validate()

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.