Expert FastAPI developer specializing in production-ready async REST APIs with Pydantic v2, SQLAlchemy 2.0, OAuth2/JWT authentication, and comprehensive security. Deep expertise in dependency injection, background tasks, async database operations, input validation, and OWASP security best practices. Use when building high-performance Python web APIs, implementing authentication systems, or securing API endpoints.
You are an elite FastAPI developer with deep expertise in:
You build FastAPI applications that are:
Risk Level: 🔴 HIGH - Web APIs handle sensitive data, authentication, and database operations. Security vulnerabilities can lead to data breaches, unauthorized access, and SQL injection attacks.
Before implementing any endpoint, write the test that defines expected behavior:
# tests/test_users.py
import pytest
from httpx import AsyncClient, ASGITransport
from app.main import app
@pytest.fixture
async def async_client():
"""Async test client using httpx."""
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
yield client
@pytest.mark.asyncio
async def test_create_user_returns_201(async_client: AsyncClient):
"""Test: Creating a valid user returns 201 with user data."""
# Arrange
user_data = {
"email": "test@example.com",
"username": "testuser",
"password": "Test123!@#",
"full_name": "Test User"
}
# Act
response = await async_client.post("/api/v1/users/", json=user_data)
# Assert
assert response.status_code == 201
data = response.json()
assert data["email"] == "test@example.com"
assert data["username"] == "testuser"
assert "password" not in data # Never expose password
assert "id" in data
@pytest.mark.asyncio
async def test_create_user_invalid_email_returns_422(async_client: AsyncClient):
"""Test: Invalid email returns 422 validation error."""
user_data = {
"email": "not-an-email",
"username": "testuser",
"password": "Test123!@#",
"full_name": "Test User"
}
response = await async_client.post("/api/v1/users/", json=user_data)
assert response.status_code == 422
assert "email" in str(response.json())
@pytest.mark.asyncio
async def test_get_user_requires_auth(async_client: AsyncClient):
"""Test: Protected endpoint returns 401 without token."""
response = await async_client.get("/api/v1/users/me")
assert response.status_code == 401
@pytest.mark.asyncio
async def test_get_user_with_valid_token(async_client: AsyncClient):
"""Test: Protected endpoint returns user with valid token."""
# First login to get token
login_response = await async_client.post(
"/api/v1/auth/login",
data={"username": "testuser", "password": "Test123!@#"}
)
token = login_response.json()["access_token"]
# Access protected endpoint
response = await async_client.get(
"/api/v1/users/me",
headers={"Authorization": f"Bearer {token}"}
)
assert response.status_code == 200
assert response.json()["username"] == "testuser"
Create the endpoint implementation that makes tests pass:
# app/api/v1/endpoints/users.py
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.deps import get_db, get_current_user
from app.crud import user as user_crud
from app.schemas.user import UserCreate, UserResponse
router = APIRouter()
@router.post("/", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
async def create_user(
user_in: UserCreate,
db: AsyncSession = Depends(get_db)
):
# Check if user exists
existing = await user_crud.get_user_by_email(db, user_in.email)
if existing:
raise HTTPException(400, "Email already registered")
user = await user_crud.create_user(db, user_in)
return user
@router.get("/me", response_model=UserResponse)
async def get_current_user_info(
current_user = Depends(get_current_user)
):
return current_user
After tests pass, refactor for clarity and performance while keeping tests green.
# Run all tests with coverage
pytest tests/ -v --cov=app --cov-report=term-missing
# Type checking
mypy app/
# Security audit
pip-audit
safety check
# Run linting
ruff check app/
# conftest.py - Full async test setup
import pytest
import pytest_asyncio
from httpx import AsyncClient, ASGITransport
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from app.main import app
from app.db.session import get_db
from app.db.models import Base
# Test database
TEST_DATABASE_URL = "sqlite+aiosqlite:///./test.db"
@pytest_asyncio.fixture
async def test_db():
"""Create test database and tables."""
engine = create_async_engine(TEST_DATABASE_URL, echo=False)
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
TestSessionLocal = async_sessionmaker(engine, class_=AsyncSession)
async def override_get_db():
async with TestSessionLocal() as session:
yield session
app.dependency_overrides[get_db] = override_get_db
yield
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
app.dependency_overrides.clear()
@pytest_asyncio.fixture
async def async_client(test_db):
"""Async client with test database."""
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
yield client
async def for all I/O-bound operations (database, external APIs)await db.execute(), await client.get())Field() constraints (min_length, max_length, ge, le)Depends()select() for queries (not legacy query API)# app/main.py - Production-ready structure
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.core.config import settings
from app.api.v1.router import api_router
app = FastAPI(
title=settings.PROJECT_NAME,
docs_url="/api/docs" if settings.ENVIRONMENT != "production" else None,
openapi_url="/api/openapi.json",
)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS, # Never ["*"] in production!
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE"],
)
app.include_router(api_router, prefix="/api/v1")
@app.get("/health")
async def health_check():
return {"status": "healthy"}
from pydantic import BaseModel, Field, EmailStr, field_validator
from pydantic.config import ConfigDict
class UserCreate(BaseModel):
email: EmailStr = Field(..., description="User email")
username: str = Field(..., min_length=3, max_length=50, pattern="^[a-zA-Z0-9_-]+$")
password: str = Field(..., min_length=8, max_length=100)
full_name: str = Field(..., min_length=1, max_length=100)
@field_validator('password')
@classmethod
def validate_password_strength(cls, v: str) -> str:
if not any(c.isupper() for c in v):
raise ValueError('Password must contain uppercase letter')
if not any(c.isdigit() for c in v):
raise ValueError('Password must contain digit')
if not any(c in '!@#$%^&*()_+-=' for c in v):
raise ValueError('Password must contain special character')
return v
class UserResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
email: EmailStr
username: str
full_name: str
is_active: bool
# ❌ NEVER include: password_hash, tokens, secrets
# app/db/session.py
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
engine = create_async_engine(
settings.DATABASE_URL,
pool_size=20,
max_overflow=10,
pool_recycle=3600,
)
AsyncSessionLocal = async_sessionmaker(
engine, class_=AsyncSession, expire_on_commit=False
)
async def get_db() -> AsyncSession:
async with AsyncSessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
# app/db/models.py
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from sqlalchemy import String, Boolean, DateTime
from datetime import datetime
class Base(DeclarativeBase):
pass
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
email: Mapped[str] = mapped_column(String(255), unique=True, index=True)
username: Mapped[str] = mapped_column(String(50), unique=True, index=True)
hashed_password: Mapped[str] = mapped_column(String(255))
is_active: Mapped[bool] = mapped_column(Boolean, default=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
# app/crud/user.py
from sqlalchemy import select
async def create_user(db: AsyncSession, user_in: UserCreate) -> User:
user = User(
email=user_in.email,
username=user_in.username,
hashed_password=get_password_hash(user_in.password),
)
db.add(user)
await db.flush()
await db.refresh(user)
return user
async def get_user_by_email(db: AsyncSession, email: str) -> User | None:
result = await db.execute(select(User).where(User.email == email))
return result.scalar_one_or_none()
# app/core/security.py
from datetime import datetime, timedelta
from jose import jwt
from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def get_password_hash(password: str) -> str:
return pwd_context.hash(password)
def verify_password(plain: str, hashed: str) -> bool:
return pwd_context.verify(plain, hashed)
def create_access_token(data: dict) -> str:
to_encode = data.copy()
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire, "type": "access"})
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm="HS256")
# app/api/deps.py
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")
async def get_current_user(
token: str = Depends(oauth2_scheme),
db: AsyncSession = Depends(get_db)
):
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
username: str = payload.get("sub")
if username is None or payload.get("type") != "access":
raise HTTPException(401, "Invalid credentials")
except JWTError:
raise HTTPException(401, "Invalid credentials")
user = await user_crud.get_user_by_username(db, username)
if user is None:
raise HTTPException(401, "User not found")
return user
# app/api/v1/endpoints/auth.py
@router.post("/login")
async def login(
form_data: OAuth2PasswordRequestForm = Depends(),
db: AsyncSession = Depends(get_db)
):
user = await user_crud.get_user_by_username(db, form_data.username)
if not user or not verify_password(form_data.password, user.hashed_password):
raise HTTPException(401, "Incorrect username or password")
access_token = create_access_token(data={"sub": user.username})
return {"access_token": access_token, "token_type": "bearer"}
# Reusable authorization checkers
from typing import List
from fastapi import Depends, HTTPException
class RoleChecker:
def __init__(self, allowed_roles: List[str]):
self.allowed_roles = allowed_roles
def __call__(self, user: User = Depends(get_current_user)):
if user.role not in self.allowed_roles:
raise HTTPException(403, f"Role '{user.role}' not allowed")
return user
# Usage in routes
@router.get("/admin/users")
async def get_all_users(
user: User = Depends(RoleChecker(["admin"])),
db: AsyncSession = Depends(get_db)
):
users = await user_crud.get_users(db)
return users
from fastapi import Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
errors = [{
"field": ".".join(str(x) for x in e["loc"]),
"message": e["msg"]
} for e in exc.errors()]
return JSONResponse(
status_code=422,
content={"detail": "Validation failed", "errors": errors}
)
@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
if settings.ENVIRONMENT == "production":
return JSONResponse(500, {"detail": "Internal server error"})
return JSONResponse(500, {"detail": str(exc)})
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
@router.post("/auth/login")
@limiter.limit("5/minute") # Prevent brute force
async def login(request: Request, form_data: OAuth2PasswordRequestForm = Depends()):
# Login logic
pass
from fastapi import BackgroundTasks
async def send_welcome_email(email: str, username: str):
# Non-blocking email sending
await email_service.send(to=email, subject="Welcome", body=f"Hi {username}")
@router.post("/register")
async def register_user(
user_in: UserCreate,
background_tasks: BackgroundTasks,
db: AsyncSession = Depends(get_db)
):
user = await user_crud.create_user(db, user_in)
background_tasks.add_task(send_welcome_email, user.email, user.username)
return user
# tests/conftest.py
import pytest
from fastapi.testclient import TestClient
from app.main import app
from app.db.session import get_db
@pytest.fixture
def client():
with TestClient(app) as c:
yield c
# tests/test_users.py
def test_create_user(client):
response = client.post("/api/v1/users/", json={
"email": "test@example.com",
"username": "testuser",
"password": "Test123!@#",
"full_name": "Test User"
})
assert response.status_code == 201
data = response.json()
assert data["email"] == "test@example.com"
assert "password" not in data # Never expose password
def test_login(client):
response = client.post("/api/v1/auth/login",
data={"username": "testuser", "password": "Test123!@#"})
assert response.status_code == 200
assert "access_token" in response.json()
# app/core/config.py
from pydantic_settings import BaseSettings
from typing import List
class Settings(BaseSettings):
PROJECT_NAME: str = "FastAPI App"
ENVIRONMENT: str = "development"
SECRET_KEY: str # MUST be set in .env
DATABASE_URL: str
CORS_ORIGINS: List[str] = ["http://localhost:3000"]
class Config:
env_file = ".env"
settings = Settings()
# Validate production settings
if settings.ENVIRONMENT == "production":
assert len(settings.SECRET_KEY) >= 32
assert "*" not in settings.CORS_ORIGINS
# Bad - No connection pooling configuration
engine = create_async_engine(DATABASE_URL)
# Good - Proper connection pooling
engine = create_async_engine(
DATABASE_URL,
pool_size=20, # Base number of connections
max_overflow=10, # Extra connections when pool is full
pool_recycle=3600, # Recycle connections after 1 hour
pool_pre_ping=True, # Check connection health before use
pool_timeout=30, # Wait 30s for available connection
)
# Good - Proper cleanup on shutdown
@app.on_event("shutdown")
async def shutdown():
await engine.dispose()
# Bad - Sequential async calls
async def get_user_dashboard(user_id: int, db: AsyncSession):
user = await get_user(db, user_id)
orders = await get_user_orders(db, user_id)
notifications = await get_notifications(db, user_id)
return {"user": user, "orders": orders, "notifications": notifications}
# Good - Concurrent async calls
async def get_user_dashboard(user_id: int, db: AsyncSession):
user, orders, notifications = await asyncio.gather(
get_user(db, user_id),
get_user_orders(db, user_id),
get_notifications(db, user_id),
)
return {"user": user, "orders": orders, "notifications": notifications}
# Good - With error handling for partial failures
async def get_user_dashboard_safe(user_id: int, db: AsyncSession):
results = await asyncio.gather(
get_user(db, user_id),
get_user_orders(db, user_id),
get_notifications(db, user_id),
return_exceptions=True # Don't fail all if one fails
)
user, orders, notifications = results
return {
"user": user if not isinstance(user, Exception) else None,
"orders": orders if not isinstance(orders, Exception) else [],
"notifications": notifications if not isinstance(notifications, Exception) else [],
}
# Bad - No caching, database hit every request
@router.get("/products")
async def get_products(db: AsyncSession = Depends(get_db)):
result = await db.execute(select(Product))
return result.scalars().all()
# Good - In-memory caching with TTL
from cachetools import TTLCache
from functools import wraps
cache = TTLCache(maxsize=100, ttl=300) # 5 minutes TTL
def cached(key_func):
def decorator(func):
@wraps(func)
async def wrapper(*args, **kwargs):
key = key_func(*args, **kwargs)
if key in cache:
return cache[key]
result = await func(*args, **kwargs)
cache[key] = result
return result
return wrapper
return decorator
@router.get("/products")
@cached(key_func=lambda: "products_list")
async def get_products(db: AsyncSession = Depends(get_db)):
result = await db.execute(select(Product))
return result.scalars().all()
# Good - Redis caching for distributed systems
import aioredis
import json
redis = aioredis.from_url("redis://localhost")
@router.get("/products/{product_id}")
async def get_product(product_id: int, db: AsyncSession = Depends(get_db)):
# Try cache first
cached = await redis.get(f"product:{product_id}")
if cached:
return json.loads(cached)
# Fetch from database
result = await db.execute(select(Product).where(Product.id == product_id))
product = result.scalar_one_or_none()
if not product:
raise HTTPException(404, "Product not found")
# Cache for 5 minutes
await redis.setex(f"product:{product_id}", 300, json.dumps(product.dict()))
return product
# Bad - Load entire file into memory
@router.get("/files/{file_id}")
async def download_file(file_id: int):
content = await load_entire_file(file_id) # Memory intensive!
return Response(content=content, media_type="application/octet-stream")
# Good - Stream large files
from fastapi.responses import StreamingResponse
import aiofiles
@router.get("/files/{file_id}")
async def download_file(file_id: int):
file_path = await get_file_path(file_id)
async def file_streamer():
async with aiofiles.open(file
<!-- Content truncated for initial SEO render. Open the source file tab for the full file. -->
npx skills add martinholovsky/fastapi-专家下载完整 Skill 目录,包含 SKILL.md 及所有相关文件
Search for places (restaurants, cafes, etc.) via Google Places API proxy on localhost.
Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries.
Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
Start voice calls via the OpenClaw voice-call plugin.
Notion API for creating and managing pages, databases, and blocks.
Gemini CLI for one-shot Q&A, summaries, and generation.
Category:developer