Jeffallan/claude-skills / skills/fastapi-expert
fastapi-expert
VerifiedUse 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.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 6.9 KB |
| references/async-sqlalchemy.md | markdown | 4.0 KB |
| references/authentication.md | markdown | 4.3 KB |
| references/endpoints-routing.md | markdown | 4.0 KB |
| references/migration-from-django.md | markdown | 27.0 KB |
| references/pydantic-v2.md | markdown | 3.3 KB |
| references/testing-async.md | markdown | 4.5 KB |
references/authentication.md
View on GitHub# Authentication
## OAuth2 Password Flow
```python
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
```python
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
```python
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
```python
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
```python
@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 |
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| deprecation-and-migrationaddyosmani/agent-skillsManages deprecation and migration. Use when removing old systems, APIs, or features. Use when migrating users from one implementation to another. Use when migrating a database schema in production, such as renaming or dropping a column without downtime (expand/contract). Use when deciding whether to maintain or sunset existing code. | Stars: 119k | Updated | Claude CodeCodex | Verified | Install |
| performance-optimizationaddyosmani/agent-skillsOptimizes application performance across frontend, backend, queries, and databases. Use when performance requirements exist, when you suspect performance regressions, when Core Web Vitals or load times need improvement, when N+1 query patterns need fixing, or when profiling reveals bottlenecks. | Stars: 119k | Updated | Claude CodeCodex | Verified | Install |
| agent-cost-reportthedotmack/claude-memBelievable agent cost report for any period, default the last 7 full days PT, not counting today. Measured tokens from Claude Code transcripts priced at OpenRouter list prices (ESTIMATED), measured provider spend when a sanctioned source exists, note-taker cost separate, Timing-style HTML/PDF plus report.json, line-items.csv, evidence.json. | Stars: 118k | Updated | Claude CodeCodex | Verified | Install |
| agent-cost-reportthedotmack/claude-memBelievable agent cost report for any period, default the last 7 full days PT, not counting today. Measured tokens from Claude Code transcripts priced at OpenRouter list prices (ESTIMATED), measured provider spend when a sanctioned source exists, note-taker cost separate, Timing-style HTML/PDF plus report.json, line-items.csv, evidence.json. | Stars: 118k | Updated | Claude CodeCodex | Verified | Install |