fastapi
БесплатноБез исполняемых скриптовНе проверенFastAPI is a Python web framework for building HTTP and WebSocket APIs from type-annotated functions, with request validation by Pydantic and automatic…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
FastAPI
Overview
FastAPI is built on Starlette (ASGI) and Pydantic v2. Path operation functions declare their inputs with type hints (path, query, header, body); FastAPI validates them, returns 422 with details on bad input, serialises the return value through response_model, and serves interactive docs at /docs (Swagger UI) and /redoc plus the schema at /openapi.json. The code below was run with fastapi 0.162.0, Starlette 1.10, Pydantic 2.14 and pytest 9.
Instructions
1. Install and layout
python -m venv .venv && source .venv/bin/activate
pip install "fastapi[standard]" # adds the fastapi CLI, uvicorn, httpx, email-validator
shop-api/
├── app/
│ ├── __init__.py
│ ├── main.py # FastAPI() app, lifespan, include_router
│ ├── deps.py # shared dependencies
│ └── routers/
│ ├── __init__.py
│ ├── items.py
│ └── ws.py
├── tests/
│ └── test_items.py
└── conftest.py # anyio_backend fixture
2. App and lifespan
Use lifespan for startup and shutdown work (@app.on_event is deprecated).
# app/main.py
from contextlib import asynccontextmanager
from fastapi import FastAPI
from .routers import items, ws
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.items = {} # startup: open pools, load caches
yield
app.state.items.clear() # shutdown: close connections
app = FastAPI(title="Shop API", version="1.0.0", lifespan=lifespan)
app.include_router(items.router)
app.include_router(ws.router)
3. Dependencies
Declare parameters and dependencies with Annotated; give reusable ones an alias. A Header() parameter named x_api_key reads the X-API-Key header (underscores become hyphens).
# app/deps.py
import os
from typing import Annotated
from fastapi import Depends, Header, HTTPException, Request
def get_store(request: Request) -> dict[int, dict]:
return request.app.state.items
Store = Annotated[dict[int, dict], Depends(get_store)]
async def current_user(x_api_key: Annotated[str, Header()]) -> str:
# keys come from the environment, e.g. SHOP_API_KEYS="key-maria-7f3a:maria,key-dmitri-91bc:dmitri"
keys = dict(pair.split(":") for pair in os.environ.get("SHOP_API_KEYS", "").split(",") if pair)
user = keys.get(x_api_key)
if user is None:
raise HTTPException(status_code=401, detail="Invalid API key")
return user
CurrentUser = Annotated[str, Depends(current_user)]
4. Routes, schemas, background tasks
# app/routers/items.py
from typing import Annotated
from fastapi import APIRouter, BackgroundTasks, HTTPException, Path, Query, status
from pydantic import BaseModel, Field
from ..deps import CurrentUser, Store
router = APIRouter(prefix="/items", tags=["items"])
class ItemCreate(BaseModel):
name: str = Field(min_length=1, max_length=100)
price: float = Field(gt=0)
description: str | None = None
class ItemResponse(ItemCreate):
id: int
def audit(user: str, action: str) -> None:
print(f"audit: {user} {action}")
@router.get("/", response_model=list[ItemResponse])
async def list_items(
store: Store,
skip: Annotated[int, Query(ge=0)] = 0,
limit: Annotated[int, Query(ge=1, le=100)] = 20,
):
return list(store.values())[skip : skip + limit]
@router.post("/", response_model=ItemResponse, status_code=status.HTTP_201_CREATED)
async def create_item(item: ItemCreate, store: Store, user: CurrentUser, tasks: BackgroundTasks):
new_id = max(store, default=0) + 1
store[new_id] = {"id": new_id, **item.model_dump()}
tasks.add_task(audit, user, f"created item {new_id}") # runs after the response is sent
return store[new_id]
@router.get("/{item_id}", response_model=ItemResponse)
async def get_item(item_id: Annotated[int, Path(gt=0)], store: Store):
if item_id not in store:
raise HTTPException(status_code=404, detail="Item not found")
return store[item_id]
For ORM objects add model_config = {"from_attributes": True} to the response schema. Validators use Pydantic v2 names: field_validator with @classmethod, and EmailStr needs email-validator (included in fastapi[standard]).
5. WebSocket and middleware
# app/routers/ws.py
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
router = APIRouter()
@router.websocket("/ws/{client_id}")
async def echo(websocket: WebSocket, client_id: str):
await websocket.accept()
try:
while True:
text = await websocket.receive_text()
await websocket.send_text(f"{client_id}: {text}")
except WebSocketDisconnect:
pass
# in app/main.py, after app = FastAPI(...)
import time
from fastapi import Request
@app.middleware("http")
async def add_timing_header(request: Request, call_next):
start = time.perf_counter()
response = await call_next(request)
response.headers["X-Process-Time"] = f
Установить fastapi в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл fastapi?
FastAPI is a Python web framework for building HTTP and WebSocket APIs from type-annotated functions, with request validation by Pydantic and automatic OpenAPI docs at /docs. Use this skill to create a FastAPI project, define routes and Pydantic schemas, use Depends dependency injection and Annotated parameters, add auth headers, background tasks, middleware, lifespan startup, WebSockets, tests with TestClient or httpx, and run the app with the fastapi CLI.
Как установить скилл fastapi?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл fastapi запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic