К основному содержанию
скилл CX Codex

fastapi-code-review — скилл для Claude Code: разбор и установка

Проверяет сервисы на FastAPI: выявляет синхронные блокировки в асинхронных роутах, пропущенные Depends() и ошибки в Pydantic-моделях.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add existential-birds/beagle --skill fastapi-code-review -a claude-code
Открыть на GitHub

Что делает fastapi-code-review

Скилл инспектирует эндпоинты FastAPI по фиксированному чек-листу. Он ищет синхронный ввод-вывод внутри async def — вызовы requests, open() или time.sleep, проверяет типы статусов ответов и наличие response_model. Также проверяются зависимости: вызовы через Depends() вместо ручных запусков и очистка ресурсов в генераторах с yield.

Перед выдачей замечаний агент обязан пройти три контрольных рубежа проверки с привязкой к номерам строк file:line. Без подтверждения конкретной строки в коде замечание снимается или понижается в статусе. Скилл знает особенности фреймворка и отсекает ложные срабатывания — например, отсутствие await внутри async def или возврат обычного словаря при заданном response_model нарушением не считаются.

Какие задачи решает

  • найти блокирующие синхронные вызовы requests или open() в асинхронных эндпоинтах
  • проверить корректность внедрения зависимостей через Depends() и очистку генераторов с yield
  • убедиться в наличии response_model и валидных кодов состояния HTTP в роутах
  • исключить пустые блоки except в обработчиках FastAPI

Примеры запросов агенту

  • Проведи ревью роутера в app/api/v1/users.py по чек-листу FastAPI
  • Проверь эндпоинты заказов на наличие блокирующего синхронного ввода-вывода
  • Найди в routes/auth.py ошибки внедрения зависимостей и пропущенные response_model

Как установить fastapi-code-review

1Через Skills CLI (Vercel)

npx skills add existential-birds/beagle --skill fastapi-code-review -a claude-code

2Вручную: положить файлы

~/.claude/skills/fastapi-code-review/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/fastapi-code-review/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о fastapi-code-review

Как установить fastapi-code-review в Claude Code?

Выполните команду npx skills add existential-birds/beagle --skill fastapi-code-review -a claude-code. Конфигурация сохранится в файле ~/.claude/skills/fastapi-code-review/SKILL.md.

Что делает fastapi-code-review?

Скилл анализирует эндпоинты APIRouter, инъекции через Depends(), валидацию через Pydantic и выявляет блокирующий ввод-вывод в функциях async def.

Ругается ли скилл на возврат обычного dict из эндпоинта?

Нет, если у эндпоинта объявлен response_model, возврат словаря считается корректным паттерном и скилл не создаёт замечание.

Исходный текст

SKILL.md · Apache-2.0
---
name: fastapi-code-review
description: Reviews FastAPI code for routing patterns, dependency injection, validation, and async handlers. Use when reviewing FastAPI apps, checking APIRouter setup, Depends() usage, or response models.
---

# FastAPI Code Review

## Quick Reference

| Issue Type | Reference |
|------------|-----------|
| APIRouter setup, response_model, status codes | [references/routes.md](references/routes.md) |
| Depends(), yield deps, cleanup, shared deps | [references/dependencies.md](references/dependencies.md) |
| Pydantic models, HTTPException, 422 handling | [references/validation.md](references/validation.md) |
| Async handlers, blocking I/O, background tasks | [references/async.md](references/async.md) |

## Review Checklist

- [ ] APIRouter with proper prefix and tags
- [ ] All routes specify `response_model` for type safety
- [ ] Correct HTTP methods (GET, POST, PUT, DELETE, PATCH)
- [ ] Proper status codes (200, 201, 204, 404, etc.)
- [ ] Dependencies use `Depends()` not manual calls
- [ ] Yield dependencies have proper cleanup
- [ ] Request/Response models use Pydantic
- [ ] HTTPException with status code and detail
- [ ] All route handlers are `async def`
- [ ] No blocking I/O (`requests`, `time.sleep`, `open()`)
- [ ] Background tasks for non-blocking operations
- [ ] No bare `except` in route handlers

## Valid Patterns (Do NOT Flag)

These are idiomatic FastAPI patterns that may appear problematic but are correct:

- **Pydantic validates request body automatically** - No manual validation needed when using typed Pydantic models as parameters
- **Dependency injection for database sessions** - Sessions come from `Depends()`, not passed as function arguments
- **HTTPException for all HTTP errors** - FastAPI handles conversion to proper HTTP responses
- **Async def endpoint without await** - May be using sync dependencies or simple operations; FastAPI handles this
- **Type annotation on Depends()** - This is documentation/IDE support, not a type assertion
- **Query/Path/Body defaults** - FastAPI processes these at runtime, not traditional Python defaults
- **Returning dict from endpoint** - Pydantic converts automatically if `response_model` is set

## Context-Sensitive Rules

Only flag issues when the context warrants it:

- **Flag missing validation** ONLY IF the field isn't already in a Pydantic model with validators
- **Flag missing auth** ONLY IF the endpoint isn't using `Depends()` with an auth dependency
- **Flag missing error handling** ONLY IF HTTPException isn't raised appropriately for error cases
- **Flag sync in async** ONLY IF the operation is actually blocking (file I/O, network calls, CPU-bound), not just non-async

## Gates (FastAPI-specific)

Run **once per FastAPI-related finding**, after you can anchor **`file:line`** for the handler (see [review-verification-protocol](../review-verification-protocol/SKILL.md)) and **before** the finding text ships. If a step’s pass condition is not met, **do not** assert the finding as written—gather evidence, withdraw, downgrade severity, or rephrase as a question.

### Gate 1 — Route decorator and response surface

| Step | Action | **Pass condition** |
|------|--------|---------------------|
| 1a | Open the handler’s route decorator in the repo (not from memory). | **`file:line`** for `@router.*` / `@app.*` (or the site that registers this handler). |
| 1b | Record HTTP method, `response_model=`, and `status_code=` on that decorator (or note they are absent). | **Snippet from that line** or **explicit absent** with the same **`file:line`**. |

### Gate 2 — Blocking or “should be async”

| Step | Action | **Pass condition** |
|------|--------|---------------------|
| 2a | Read the full handler body. | **`file:line` range** covering the body. |
| 2b | If claiming blocking I/O: name each blocking call (e.g. `requests.`, `open(`, `time.sleep`, sync DB/ORM). | **Each** call has **`file:line`**, or withdraw the finding if **none** after the read. |

### Gate 3 — Depends, validation, auth

| Step | Action | **Pass condition** |
|------|--------|---------------------|
| 3a | List parameters: `Depends` / `Annotated[..., Depends]`, Pydantic models, `Body`/`Query`/`Path`, `Request`/`Response`. | **Names + mechanism** tied to **`file:line`** on the signature. |
| 3b | If claiming missing auth: search the handler file (and its `APIRouter` module if separate) for `Depends`, `Security`, `HTTPBearer`, or project auth dependencies. | **Citation** to an existing hook, or **search result**: paths searched + **N matches** (zero is allowed). |
| 3c | If claiming missing validation: confirm the argument is not already a Pydantic model or constrained `Query`/`Path`/`Body`. | **Type/source** with **`file:line`**, or withdraw if validation already applies. |

## FastAPI Framework Behaviors

FastAPI + Pydantic handle many concerns automatically:
- Request validation via Pydantic models
- Response serialization via response_model
- Dependency injection for cross-cutting concerns
- Exception handling via exception handlers

Before flagging "missing" functionality, verify FastAPI isn't handling it.

## When to Load References

- Reviewing route definitions → routes.md
- Reviewing dependency injection → dependencies.md
- Reviewing Pydantic models/validation → validation.md
- Reviewing async route handlers → async.md

## Review Questions

1. Do all routes have explicit response models and status codes?
2. Are dependencies injected via Depends() with proper cleanup?
3. Do all Pydantic models validate inputs correctly?
4. Are all route handlers async and non-blocking?

## Before Submitting Findings

1. For each FastAPI-related finding, complete **Gates (FastAPI-specific)** above.
2. Load and follow [review-verification-protocol](../review-verification-protocol/SKILL.md) (Pre-Report checklist and **Verification by Issue Type**) before reporting any issue.

© existential-birds · Apache-2.0 · existential-birds/beagle

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

Все скиллы по теме «Бэкенд и API» →
mcp-builder официальный anthropics Скилл проводит через создание MCP-сервера на TypeScript или Python: от изучения протокола до тестов и оценки качества. 130 949установок claude-api официальный anthropics Справочник по Anthropic SDK и API Claude для генерации кода без устаревших параметров и выдуманных методов. 74 198установок lark-im larksuite Скилл подключает Lark IM к агенту: он отправляет сообщения, ищет историю, управляет чатами и файлами. Подойдёт для задач вокруг командных коммуникаций. CX Codex +1 472 900установок lark-event larksuite Слушает события Lark/Feishu и отдаёт их потоком NDJSON. Подходит для ботов, обработчиков сообщений и долгих подписчиков. CX Codex +1 466 800установок caveman-discover JuliusBrussee Находит точки вызова LLM в репозитории и размечает их воркфлоу для Caveman Cloud, чтобы расходы на токены не сливались в одну общую кучу. CX Codex +1 104 400установок migration JuliusBrussee Скилл задаёт правила безопасных миграций схем, данных и API с обязательным откатом. Пригодится при изменениях, где нельзя терять данные или ломать совместимость. CX Codex +1 103 900установок

Из того же набора12

tailwind-v4 Скилл для ИИ-агента, который подсказывает, как настроить Tailwind CSS v4: тема в CSS, токены дизайна, цвета OKLCH и тёмная тема. CX Codex +1 812установок react-flow-advanced Скилл учит агента внедрять сложные паттерны в React Flow: группировку узлов, историю отмены действий, автоматическую раскладку через dagre и перетаскивание элементов. CX Codex +1 631установок react-router-v7 Скилл с практиками React Router v7: подсказывает, когда брать loader, Form или fetcher, и как настраивать вложенные маршруты. CX Codex +1 572установок react-flow-architecture Архитектурные подсказки для интерфейсов на React Flow: выбор состояния, интеграций и масштаба node-based приложений. CX Codex +1 529установок vitest-testing Скилл для ИИ-агента: подсказывает, как писать тесты на Vitest — ассерты, моки, асинхронность, конфиг. Пригодится, когда в проекте уже стоит Vitest. CX Codex +1 467установок react-flow-implementation Направляет агента при создании диаграмм и визуальных редакторов на базе @xyflow/react. Помогает избежать типичных ошибок с рендером узлов и связей. CX Codex +1 362установок shadcn-ui Подсказывает агенту, как собирать компоненты на shadcn/ui: Radix, Tailwind, CVA-варианты и data-slot. CX Codex +1 351установок react-flow-code-review Проверяет код на @xyflow/react по чек-листу: антипаттерны, лишние ре-рендеры, типы. Пригодится, когда граф тормозит или ноды пересоздаются. CX Codex +1 319установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой