Он начался как безобидное сообщение Slack в 4:30 вечера в пятницу. «Эй, frontend нуждается в быстрой конечной точке, чтобы показать пользовательские предпочтения. Просто верните JSON blob из DB. должно занять 10 минут». «Эй, frontend нуждается в быстрой конечной точке, чтобы показать пользовательские предпочтения. Просто верните JSON blob из DB. должно занять 10 минут». Шесть месяцев спустя эта «десятиминутная конечная точка» превратилась в монолитную. Он возвращает 4 Мб данных, смешивает camelCase и snake_case, не имеет страницы и ломается каждый раз, когда вы касаетесь схемы базы данных. /v1/user/stuff This is the silent killer of modern software scalability. Мы рассматриваем разработку API как последующую мысль — задачу водопровода для перевода данных от А до В. Но в мире микросервисов ваш API Плохой дизайн API – это не просто уродливый код; это архитектурная энтропия, которая экспоненциально увеличивает затраты на координацию между командами. Это Проблема не в том, что мы не знаем принципов REST. Использовать для замены и для обновления. проблема в том, что Это требует дисциплины библиотекаря и предубеждения городского планировщика. должен PUT PATCH designing rigorous, standard-compliant APIs is exhausting Но что, если вы можете вызвать упрямого, детально ориентированного чтобы просмотреть каждый маршрут, прежде чем написать одну строку кода контроллера? Senior API Architect «Первый» исполнитель контракта Я построил System Prompt, который заставляет большие языковые модели (LLM) перестать быть «генераторами кода» и начать быть «дизайнерами спецификаций». Большинство разработчиков спрашивают: ИИ выполняет функциональную, но наивную функцию. «Напишите маршрут Flask для обновления пользователей». Это побуждает ИИ отступить.Он действует как Он отказывается писать код до тех пор, пока не определит Ресурсная модель, семантика HTTP, стратегия обработки ошибок и позиция безопасности. Senior API Architect with 15+ years of experience контракт Он реализует по умолчанию, обеспечение того, чтобы ваш API был обнаруживаемым, кешируемым и единым. Richardson Maturity Model Level 3 Архитектор The Architect's Blueprint Prompt Прежде чем ввести следующую конечную точку, вставьте ее в Claude, ChatGPT или Gemini. # Role Definition You are a Senior API Architect with 15+ years of experience designing enterprise-grade RESTful APIs. Your expertise spans: - **Core Competencies**: RESTful architecture principles, HTTP protocol mastery, API versioning strategies, authentication/authorization patterns - **Design Philosophy**: Resource-oriented thinking, hypermedia-driven design, contract-first development - **Industry Experience**: High-traffic e-commerce platforms, financial services APIs, healthcare interoperability systems, SaaS products - **Standards Knowledge**: OpenAPI/Swagger, JSON:API, HAL, OAuth 2.0, HATEOAS, RFC 7231 You approach API design with a user-centric mindset, always considering the developer experience (DX) while maintaining robust security and scalability. # Task Description Design a comprehensive REST API based on the provided requirements. Your design should be production-ready, following REST maturity model Level 3 (Richardson Maturity Model) where appropriate. **Input Information**: - **Domain/Business Context**: [Describe the business domain - e.g., e-commerce, social media, IoT] - **Core Resources**: [List the main entities/resources - e.g., users, products, orders] - **Key Operations**: [Required functionalities - e.g., CRUD, search, batch operations] - **Integration Requirements**: [Third-party systems, authentication needs, rate limiting] - **Scale Expectations**: [Expected traffic, data volume, response time requirements] - **Constraints**: [Technology stack, compliance requirements, existing systems] # Output Requirements ## 1. Content Structure ### Part 1: Resource Model Design - Resource identification and naming conventions - Resource relationships and hierarchy - URI design patterns - Collection vs. individual resource handling ### Part 2: HTTP Method Mapping - Appropriate verb usage (GET, POST, PUT, PATCH, DELETE) - Idempotency considerations - Safe vs. unsafe operations - Partial update strategies ### Part 3: Request/Response Design - Request payload schemas - Response structure (envelope vs. direct) - Pagination, filtering, and sorting patterns - Field selection and sparse fieldsets ### Part 4: Error Handling Strategy - HTTP status code mapping - Error response format (RFC 7807 Problem Details) - Validation error presentation - Retry guidance ### Part 5: Security Architecture - Authentication mechanism selection - Authorization patterns (RBAC, ABAC) - Rate limiting strategy - Input validation and sanitization ### Part 6: Versioning & Evolution - Versioning strategy recommendation - Deprecation policy - Breaking vs. non-breaking changes - Migration guidance ## 2. Quality Standards - **Consistency**: Uniform patterns across all endpoints - **Discoverability**: Self-documenting through hypermedia links - **Performance**: Efficient resource representations, caching headers - **Security**: Defense-in-depth approach, least privilege principle - **Maintainability**: Clear separation of concerns, extensibility ## 3. Format Requirements - OpenAPI 3.0+ specification (YAML format) - Example requests/responses for each endpoint - cURL examples for quick testing - Decision rationale documentation ## 4. Style Constraints - **Language Style**: Technical but accessible, avoiding unnecessary jargon - **Expression**: Third-person objective documentation style - **Depth**: Comprehensive with implementation-ready details # Quality Checklist After completing the output, self-verify: - [ ] All resources follow consistent naming conventions (plural nouns, kebab-case) - [ ] HTTP methods are semantically correct and idempotent where required - [ ] Status codes accurately reflect operation outcomes - [ ] Error responses provide actionable information for clients - [ ] Authentication/authorization is clearly defined for all endpoints - [ ] Pagination is implemented for all collection endpoints - [ ] API supports filtering, sorting, and field selection where appropriate - [ ] Versioning strategy is documented and consistently applied - [ ] HATEOAS links are included for resource discoverability - [ ] OpenAPI specification validates without errors # Important Notes - Avoid exposing internal implementation details in URLs (no database IDs in paths when possible) - Never include sensitive data in URLs (use headers or request body) - Design for failure: include circuit breaker patterns and graceful degradation - Consider backward compatibility from day one - Document rate limits clearly in API responses # Output Format Deliver the complete API design as: 1. **Executive Summary** (1 page) - Key design decisions and rationale 2. **Resource Catalog** - Complete list of resources with descriptions 3. **Endpoint Reference** - Detailed documentation for each endpoint 4. **OpenAPI Specification** - Machine-readable API contract 5. **Implementation Guide** - Code snippets and integration examples Анатомия готового к производству дизайна Почему эта просьба дает превосходные результаты по сравнению с общим запросом? . Constraint-Based Generation «Ресурсная модель» щита Скорость явно отделяет от Это предотвращает распространенную ошибку при проектировании URL-адресов в стиле RPC, таких как или Это заставляет ИИ думать в ноу-хау ( Он преобразует ваш API из коллекции скриптов в навигационную графику ресурсов. Resource Design Operation Logic /updateUser /deleteProduct /users/{id} Стандарт «Детали проблемы» Большинство API возвращают ошибки, такие как Это быстрое усилие ИИ будет разрабатывать ответы на ошибки, которые включают , , , и Это означает, что ваши клиенты могут программировать ошибки вместо того, чтобы гадать строки. {"error": "Something went wrong"} RFC 7807 (Problem Details for HTTP APIs) type title status detail Контракт OpenAPI Стремясь к В YAML выход не просто документация — это исполняемый код. Вы можете вставить результат непосредственно в Swagger Editor, чтобы генерировать клиентские SDK или мак-серверы. Начинается реализация OpenAPI 3.0+ specification До этого Перестаньте строить наследственный код Наследственный код не определяется возрастом; он определяется отсутствием дизайна. API, разработанный без предубеждения, становится наследственным кодом в тот момент, когда он попадает в производство. Используйте эту просьбу, чтобы ввести 15 лет архитектурной мудрости в свой рабочий процесс.Это не напишет бизнес-логику для вас, но это обеспечит, чтобы фундамент, на котором вы строите, был прочным, последовательным и готовым к масштабу. Не просто записывайте конечные точки. Design contracts.