Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

FastAPI Modern Web Development

БесплатноБез исполняемых скриптовНе проверен

Production-grade FastAPI development with async patterns, Pydantic v2, dependency injection, ML/AI endpoint design, and modern Python best practices for…

bobmatnycот bobmatnyc★ 19 звёзд на GitHub20 установок в других каталогах

Об этом скилле

FastAPI Modern Web Development

Overview

This skill provides comprehensive guidance for building production-grade FastAPI applications with modern Python patterns (2024-2025 best practices). FastAPI is the #1 framework for AI/ML APIs, combining high performance, automatic OpenAPI documentation, and intuitive async/await patterns.

When to Use This Skill

Use this skill when:

  • Building RESTful APIs for ML/AI services
  • Creating high-performance async Python web services
  • Developing data-intensive applications requiring concurrent request handling
  • Implementing microservices with automatic API documentation
  • Building APIs that require strong type safety and validation
  • Designing endpoints for LLM integration and AI workflows

Core Principles

1. Async-First Architecture

Always prefer async/await for I/O-bound operations

from fastapi import FastAPI, Depends
from sqlalchemy.ext.asyncio import AsyncSession
import httpx

app = FastAPI()

# CORRECT: Async database operations
@app.get("/users/{user_id}")
async def get_user(user_id: int, db: AsyncSession = Depends(get_db)):
    result = await db.execute(select(User).where(User.id == user_id))
    return result.scalar_one_or_none()

# CORRECT: Async external API calls
@app.get("/external-data")
async def fetch_external():
    async with httpx.AsyncClient() as client:
        response = await client.get("https://api.example.com/data")
        return response.json()

# WRONG: Blocking synchronous calls in async context
@app.get("/bad-example")
async def bad_handler():
    time.sleep(5)  # Blocks entire event loop!
    return {"status": "done"}

Why: FastAPI runs on ASGI (asyncio). Blocking calls prevent other requests from processing, degrading performance under load.

2. Pydantic v2 Models for Type Safety

Use Pydantic models for all request/response validation

from pydantic import BaseModel, Field, field_validator, ConfigDict
from datetime import datetime
from typing import Optional

class UserCreate(BaseModel):
    """Request model for user creation"""
    model_config = ConfigDict(str_strip_whitespace=True)

    username: str = Field(..., min_length=3, max_length=50)
    email: str = Field(..., pattern=r'^[\w\.-]+@[\w\.-]+\.\w+$')
    age: Optional[int] = Field(None, ge=13, le=120)

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

class UserResponse(BaseModel):
    """Response model - never expose internal fields"""
    model_config = ConfigDict(from_attributes=True)  # Pydantic v2

    id: int
    username: str
    email: str
    created_at: datetime
    # DON'T expose: password_hash, internal_flags, etc.

@app.post("/users", response_model=UserResponse, status_code=201)
async def create_user(user: UserCreate, db: AsyncSession = Depends(get_db)):
    db_user = User(**user.model_dump())  # Pydantic v2 syntax
    db.add(db_user)
    await db.commit()
    await db.refresh(db_user)
    return db_user

Key Updates for Pydantic v2:

  • Config → model_config = ConfigDict(...)
  • orm_mode=True → from_attributes=True
  • dict() → model_dump()
  • @validator → @field_validator

3. Dependency Injection for Loose Coupling

Use FastAPI's dependency injection for reusable components

from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker

# Database session dependency
async_engine = create_async_engine("postgresql+asyncpg://...")
AsyncSessionLocal = sessionmaker(
    async_engine, class_=AsyncSession, expire_on_commit=False
)

async def get_db() -> AsyncSession:
    async with AsyncSessionLocal() as session:
        yield session

# Authentication dependency
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

async def get_current_user(
    token: str = Depends(oauth2_scheme),
    db: AsyncSession = Depends(get_db)
) -> User:
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    payload = verify_token(token)
    if payload is None:
        raise credentials_exception

    user = await db.get(User, payload.get("sub"))
    if user is None:
        raise credentials_exception
    return user

# Use dependencies in route
@app.get("/me")
async def read_users_me(current_user: User = Depends(get_current_user)):
    return current_user

Benefits: Automatic injection, easy testing with override_dependency, shared logic across routes.

4. Structured Error Handling

Always use HTTPException with proper status codes

from fastapi import HTTPException, status

@app.get("/items/{item_id}")
async def get_item(
Полный SKILL.md на GitHub

Установить FastAPI Modern Web Development в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл FastAPI Modern Web Development?

Production-grade FastAPI development with async patterns, Pydantic v2, dependency injection, ML/AI endpoint design, and modern Python best practices for building high-performance REST APIs

Как установить скилл FastAPI Modern Web Development?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл FastAPI Modern Web Development запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить FastAPI Modern Web Development с