api
БесплатноБез исполняемых скриптовНе проверенDraftForge frontend↔backend API binding: axios client, Zod response schemas, TanStack Query hooks, DRF errors, generated Zod from pydantic models, and…
от kettleofketchup★ 16 звёзд на GitHubОб этом скилле
API binding
Every HTTP call from the frontend goes through one client, returns data that a Zod schema has parsed, and reaches components through a query hook. The Zod schema either comes from a backend pydantic model (generated) or mirrors a DRF serializer (hand-written).
WebSocket messages (app/lib/websocket/) are out of scope.
Layout
New code lives in a feature folder (app/features/promotion/ is the reference):
| File | Holds |
|---|---|
schemas.ts |
Zod schemas + z.infer types, or re-exports from a *.generated.ts |
api.ts |
one async function per endpoint: call, parse, return |
queryKeys.ts / queries.ts |
key factories; useQuery / useMutation hooks |
__tests__/ |
Vitest for api.ts parsing and queries.ts invalidation |
Legacy app/components/api/*API.tsx use axios.get<T>() with no validation. Don't copy
that. When you touch one of those functions, move it to the parse pattern below.
Client
import api from '~/components/api/axios';
That instance sets the SSR/browser base URL, sends cookies, adds X-CSRFToken on
writes and handles Discord Activity auth. Never import axios directly for requests,
never use the bare instance in components/api/utils.tsx, and never call fetch. Paths
are relative to /api and keep DRF's trailing slash: api.get(/events/${id}/).
Pass query strings via { params }.
Endpoint functions
export async function getPromoTemplates(orgId: number): Promise<PromoTemplate[]> {
const response = await api.get(`${base(orgId)}/templates/`);
return z.array(PromoTemplateSchema).parse(response.data);
}
- Parse every response body with
Schema.parse. Don't useapi.get<T>(): the type argument is an unchecked cast. - Keep the wire field names. DRF and pydantic API models send snake_case, so schemas use snake_case too. Rename only in a mapping function, never in the schema.
- Type request bodies: generated request type, form schema output, or a local
type. - Map "expected" statuses at the edge:
isAxiosError(err) && err.response?.status === 404→ returnnull(seegetPasswordInfoinapp/components/lobby/api.ts). Let the rest throw.
Where the schema comes from
- The backend has (or should have) a pydantic model for the payload. Use a
generated binding; don't hand-write it. Follow
references/pydantic-bindings.md. Good fits: views thatModel.model_validate(request.data)and returnmodel.model_dump(mode="json"), new non-model endpoints, and static catalogues. - The endpoint returns a DRF serializer. Hand-write the Zod schema in
schemas.ts, field for field from the serializer (fields,read_only,SerializerMethodFieldreturn types,allow_null→.nullable(),required=False→.optional()). Note the serializer path in a one-line comment above the schema. For a payload where drift would hurt, pin it with a fixture both test suites read (backend/org/tests/render_fixture.json↔frontend/app/features/promotion/__tests__/, compared withcmpin theunitCI job).
Don't add drf-spectacular/OpenAPI codegen for one endpoint. Raise it with the user first.
Backend validation: pydantic first
Validate request bodies and stored JSON config with pydantic models, not hand-written
isinstance/regex checks in the view or a helper module.
- Put rules in the model:
Annotatedtypes withStringConstraintsorAfterValidatorfor field shapes,field_validatorfor one field,model_validator(mode="after")for cross-field rules. - Keep API error codes stable with
pydantic_core.PydanticCustomError("<code>", ...), then map theValidationErrorto the code the endpoint returns. - Keep outside the model only what must run before it: size and depth guards on raw input, and normalisation that copies the validated model.
- Example:
backend/org/api_connections/types.py(rules) andbackend/org/api_connections/schemas.py(validate_connection_config). - DRF serializers stay for model-backed CRUD that already uses them; new non-model payloads get a pydantic model.
Queries and mutations
- Key factories in
queryKeys.ts, with scope first and the viewer in the key when the response depends on permissions:promotionKeys.templates(orgId, viewerPk)(app/features/org-features/queryKeys.ts). useQuery({ queryKey, queryFn: () => getX(...), enabled }). Gate on permission flags rather than letting the request 403.- Mutations invalidate or
setQueryDatathe affected keys inonSuccess; prefix keys let you invalidate a whole feature.
Errors
- User-facing message:
extractApiError(err)from~/lib/apiError(handles DRFerror/detail/ field-list shapes), thentoast.error(msg ?? fallback). - A
ZodErrorfromparseis a contract bug, not a user error. Don't swallow it. Log it viagetLoggerand fix the schema or the backend. - Field errors on forms: map DRF
{field: [msg]}onto React Hook Form `form.s
Установить api в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл api?
DraftForge frontend↔backend API binding: axios client, Zod response schemas, TanStack Query hooks, DRF errors, generated Zod from pydantic models, and pydantic-first backend validation. Use when adding or changing an endpoint call or validating a request body or stored config.
Как установить скилл api?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл api запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic