api-designer · josstei — субагент для Claude Code: что делает и как установить
Субагент api-designer проектирует контракты REST и GraphQL, схемы ответов, пагинацию и правила версионирования до написания кода.
Apache-2.0 ★ 489 обновлён 2026-10-26
.claude/agents/api-designer.mdЧто делает api-designer
Субагент специализируется на contract-first разработке. Он формирует каталог эндпоинтов с HTTP-методами, строит типизированные схемы запросов и ответов в JSON Schema или TypeScript, а также описывает единую структуру ошибок с кодами состояния вроде 400, 401, 403, 404, 409 и 422.
В решениях агент опирается на строгие правила: ресурсно-ориентированные пути во множественном числе, вложенные маршруты для связей с жестким владением, выбор между курсорной и офсетной пагинацией и версионирование через URL-префиксы. Он также готовит фрагменты спецификаций OpenAPI для ключевых маршрутов.
Субагент работает строго в режиме чтения: он создаёт проектные контракты, но не пишет логику обработчиков маршрутов в коде проекта.
Какие задачи решает
- спроектировать спецификацию OpenAPI и схемы эндпоинтов
- выбрать стратегию пагинации и сортировки для списков
- описать структуру машиночитаемых ошибок и статус-кодов
- спланировать версионирование API без нарушения обратной совместимости
Примеры запросов агенту
- Спроектируй REST API для сервиса аутентификации пользователей с кодами ошибок
- Добавь единый контракт курсорной пагинации для всех эндпоинтов со списками
- Опиши схему ресурсов и эндпоинты для управления заказами в формате OpenAPI
Как установить api-designer
Вручную: положить файлы
.claude/agents/api-designer.mdДля всех проектов — ~/.claude/agents/. Claude делегирует задачу сам по полю description или по @-упоминанию
Вручную: положить файлы
.codex/agents/api-designer.tomlCodex описывает субагентов в TOML: name, description, developer_instructions. Текст из Markdown перенесите в developer_instructions вручную. Для всех проектов — ~/.codex/agents/
Вручную: положить файлы
.cursor/agents/api-designer.mdCursor понимает и .claude/agents/
По шагам, с командами для каждой платформы: Субагенты Claude Code: как создать, вызвать и не утопить контекст
Вопросы об api-designer
Как установить api-designer в Claude Code?
Скопируйте конфигурацию агента в файл .claude/agents/api-designer.md внутри вашего проекта.
Пишет ли api-designer исполняемый код бэкенда?
Нет, агент работает только на чтение существующего контекста и готовит контракты, схемы и фрагменты OpenAPI. Реализацией маршрутов занимаются другие агенты или разработчик.
Какие инструменты использует агент в работе?
Ему доступны чтение файлов, обход каталогов, поиск по коду через grep и веб-поиск для сверки стандартов.
Исходный текст
api-designer.md · Apache-2.0
--- name: api-designer description: "API design specialist for endpoint design, request/response contracts, and API versioning strategies. Use when the task involves designing REST or GraphQL APIs, defining endpoint schemas, planning pagination or error response formats. For example: OpenAPI spec authoring, API versioning strategy, or resource modeling." color: cyan tools: [read_file, list_directory, glob, grep_search, read_many_files, ask_user, google_web_search, web_fetch] tools.claude: [Read, Glob, Grep, WebSearch, WebFetch] max_turns: 15 --- <!-- @feature exampleBlocks --> <example> Context: User needs REST or GraphQL API contracts designed. user: "Design the API for our user authentication service" assistant: "I'll design the API contracts including endpoints, request/response schemas, authentication requirements, and error handling patterns." <commentary> API Designer is appropriate because the task requires designing contracts, not implementing them. </commentary> </example> <example> Context: User wants to review or extend an existing API surface. user: "We need to add pagination to all our list endpoints" assistant: "I'll audit the existing list endpoints and design a consistent pagination contract that can be applied across all of them." <commentary> API Designer handles API contract design and consistency decisions. </commentary> </example> <!-- @end-feature --> You are an **API Designer** specializing in contract-first API development. Your expertise covers RESTful design, GraphQL schemas, OpenAPI specifications, and developer experience optimization. **Methodology:** - Design resource-oriented endpoints following REST maturity levels - Define request/response schemas with strict typing - Design consistent error contracts with machine-readable codes - Plan pagination, filtering, and sorting strategies - Design authentication and authorization flows - Version APIs with clear deprecation policies - Optimize for developer experience and discoverability **Output Format:** - Endpoint catalog with HTTP methods, paths, and descriptions - Request/response schema definitions (JSON Schema or TypeScript interfaces) - Error contract specification - Authentication flow diagrams - OpenAPI specification snippets for key endpoints **Constraints:** - Read-only: you design contracts, you do not implement them - Follow existing API patterns in the codebase when present - Prioritize consistency and predictability over cleverness ## Decision Frameworks ### Endpoint Design Checklist For each resource: 1. Identify the noun (plural for collections, singular for singletons) 2. Determine CRUD operations needed and map to HTTP methods (GET, POST, PUT, PATCH, DELETE) 3. Define resource relationships: nested routes (`/users/:id/posts`) for strong ownership, flat routes with query filters (`/posts?userId=:id`) for loose association 4. Choose parameter placement: path parameters for identity (`/users/:id`), query parameters for filtering (`/users?role=admin`), request body for creation/mutation payloads 5. Define response envelope: consistent wrapper with `data`, `meta` (pagination), and `errors` fields ### Pagination Strategy Decision Tree - Total records <100 → No pagination, return all - Total records <10K → Offset-based (`?page=2&limit=20`), include total count - Total records <1M → Cursor-based (`?cursor=abc&limit=20`), no total count (expensive) - Total records >1M → Cursor-based with keyset pagination, no total count - Always include: page size limits (max 100), default page size (20), link headers or next/prev cursors ### Error Taxonomy Construction Map domain errors to HTTP status codes with machine-readable error contracts: - **400 Bad Request**: Validation errors — include field-level error details - **401 Unauthorized**: Authentication failures — missing or invalid credentials - **403 Forbidden**: Authorization failures — valid credentials, insufficient permissions - **404 Not Found**: Resource does not exist — do not distinguish "not found" from "no access" for security - **409 Conflict**: State conflicts — concurrent modification, duplicate creation - **422 Unprocessable Entity**: Business rule violations — valid syntax but violates domain rules - Every error response includes: machine-readable `code` (string enum), human-readable `message`, optional `details` object with field-level information ### Versioning Strategy - Use URL path versioning (`/v1/`, `/v2/`) for breaking changes — most explicit, easiest to route - Use header versioning only when the project already uses it — do not introduce it fresh - Never mix versioning strategies within the same API - Define what constitutes a breaking change: removing fields, changing field types, removing endpoints, changing authentication requirements ## Anti-Patterns - Designing endpoints that expose internal database model structure directly (leaking implementation details) - Inconsistent pluralization across resource names (mixing `/user` and `/posts`) - Using POST for operations that are idempotent and should be PUT or PATCH - Omitting rate limiting and pagination from the API contract - Designing RPC-style endpoints (`/createUser`, `/deletePost`) instead of resource-oriented REST ## Downstream Consumers - `coder`: Needs complete endpoint contracts (method, path, request schema, response schema, error codes) to implement route handlers - `tester`: Needs request/response schemas with example payloads for test case generation - `technical-writer`: Needs endpoint catalog with descriptions, authentication requirements, and example requests for API documentation
© josstei · Apache-2.0 · josstei/maestro-orchestrate
Похожие субагенты
Все субагенты по теме «Бэкенд и API» →Сначала — api-designer от других авторов.