API Design Reviewer
Tier: POWERFUL
Category: Engineering / Architecture
Maintainer: Claude Skills Team
Overview
The API Design Reviewer skill provides comprehensive analysis and review of API designs, focusing on REST conventions, best practices, and industry standards. This skill helps engineering teams build consistent, maintainable, and well-designed APIs through automated linting, breaking change detection, and design scorecards.
Core Capabilities
1. API Linting and Convention Analysis
- - Resource Naming Conventions: Enforces kebab-case for resources, camelCase for fields
- HTTP Method Usage: Validates proper use of GET, POST, PUT, PATCH, DELETE
- URL Structure: Analyzes endpoint patterns for consistency and RESTful design
- Status Code Compliance: Ensures appropriate HTTP status codes are used
- Error Response Formats: Validates consistent error response structures
- Documentation Coverage: Checks for missing descriptions and documentation gaps
2. Breaking Change Detection
- - Endpoint Removal: Detects removed or deprecated endpoints
- Response Shape Changes: Identifies modifications to response structures
- Field Removal: Tracks removed or renamed fields in API responses
- Type Changes: Catches field type modifications that could break clients
- Required Field Additions: Flags new required fields that could break existing integrations
- Status Code Changes: Detects changes to expected status codes
3. API Design Scoring and Assessment
- - Consistency Analysis (30%): Evaluates naming conventions, response patterns, and structural consistency
- Documentation Quality (20%): Assesses completeness and clarity of API documentation
- Security Implementation (20%): Reviews authentication, authorization, and security headers
- Usability Design (15%): Analyzes ease of use, discoverability, and developer experience
- Performance Patterns (15%): Evaluates caching, pagination, and efficiency patterns
REST Design Principles
Resource Naming Conventions
CODEBLOCK0
HTTP Method Usage
- - GET: Retrieve resources (safe, idempotent)
- POST: Create new resources (not idempotent)
- PUT: Replace entire resources (idempotent)
- PATCH: Partial resource updates (not necessarily idempotent)
- DELETE: Remove resources (idempotent)
URL Structure Best Practices
CODEBLOCK1
Versioning Strategies
1. URL Versioning (Recommended)
/api/v1/users
/api/v2/users
Pros: Clear, explicit, easy to route
Cons: URL proliferation, caching complexity
2. Header Versioning
GET /api/users
Accept: application/vnd.api+json;version=1
Pros: Clean URLs, content negotiation
Cons: Less visible, harder to test manually
3. Media Type Versioning
GET /api/users
Accept: application/vnd.myapi.v1+json
Pros: RESTful, supports multiple representations
Cons: Complex, harder to implement
4. Query Parameter Versioning
/api/users?version=1
Pros: Simple to implement
Cons: Not RESTful, can be ignored
Pagination Patterns
Offset-Based Pagination
CODEBLOCK6
Cursor-Based Pagination
CODEBLOCK7
Page-Based Pagination
CODEBLOCK8
Error Response Formats
Standard Error Structure
CODEBLOCK9
HTTP Status Code Usage
- - 400 Bad Request: Invalid request syntax or parameters
- 401 Unauthorized: Authentication required
- 403 Forbidden: Access denied (authenticated but not authorized)
- 404 Not Found: Resource not found
- 409 Conflict: Resource conflict (duplicate, version mismatch)
- 422 Unprocessable Entity: Valid syntax but semantic errors
- 429 Too Many Requests: Rate limit exceeded
- 500 Internal Server Error: Unexpected server error
Authentication and Authorization Patterns
Bearer Token Authentication
CODEBLOCK10
API Key Authentication
CODEBLOCK11
OAuth 2.0 Flow
CODEBLOCK12
Role-Based Access Control (RBAC)
CODEBLOCK13
Rate Limiting Implementation
Headers
CODEBLOCK14
Response on Limit Exceeded
CODEBLOCK15
HATEOAS (Hypermedia as the Engine of Application State)
Example Implementation
CODEBLOCK16
Idempotency
Idempotent Methods
- - GET: Always safe and idempotent
- PUT: Should be idempotent (replace entire resource)
- DELETE: Should be idempotent (same result)
- PATCH: May or may not be idempotent
Idempotency Keys
CODEBLOCK17
Backward Compatibility Guidelines
Safe Changes (Non-Breaking)
- - Adding optional fields to requests
- Adding fields to responses
- Adding new endpoints
- Making required fields optional
- Adding new enum values (with graceful handling)
Breaking Changes (Require Version Bump)
- - Removing fields from responses
- Making optional fields required
- Changing field types
- Removing endpoints
- Changing URL structures
- Modifying error response formats
OpenAPI/Swagger Validation
Required Components
- - API Information: Title, description, version
- Server Information: Base URLs and descriptions
- Path Definitions: All endpoints with methods
- Parameter Definitions: Query, path, header parameters
- Request/Response Schemas: Complete data models
- Security Definitions: Authentication schemes
- Error Responses: Standard error formats
Best Practices
- - Use consistent naming conventions
- Provide detailed descriptions for all components
- Include examples for complex objects
- Define reusable components and schemas
- Validate against OpenAPI specification
Performance Considerations
Caching Strategies
CODEBLOCK18
Efficient Data Transfer
- - Use appropriate HTTP methods
- Implement field selection (
?fields=id,name,email) - Support compression (gzip)
- Implement efficient pagination
- Use ETags for conditional requests
Resource Optimization
- - Avoid N+1 queries
- Implement batch operations
- Use async processing for heavy operations
- Support partial updates (PATCH)
Security Best Practices
Input Validation
- - Validate all input parameters
- Sanitize user data
- Use parameterized queries
- Implement request size limits
Authentication Security
- - Use HTTPS everywhere
- Implement secure token storage
- Support token expiration and refresh
- Use strong authentication mechanisms
Authorization Controls
- - Implement principle of least privilege
- Use resource-based permissions
- Support fine-grained access control
- Audit access patterns
Tools and Scripts
api_linter.py
Analyzes API specifications for compliance with REST conventions and best practices.
Features:
- - OpenAPI/Swagger spec validation
- Naming convention checks
- HTTP method usage validation
- Error format consistency
- Documentation completeness analysis
breakingchangedetector.py
Compares API specification versions to identify breaking changes.
Features:
- - Endpoint comparison
- Schema change detection
- Field removal/modification tracking
- Migration guide generation
- Impact severity assessment
api_scorecard.py
Provides comprehensive scoring of API design quality.
Features:
- - Multi-dimensional scoring
- Detailed improvement recommendations
- Letter grade assessment (A-F)
- Benchmark comparisons
- Progress tracking
Integration Examples
CI/CD Integration
CODEBLOCK19
Pre-commit Hooks
CODEBLOCK20
Best Practices Summary
- 1. Consistency First: Maintain consistent naming, response formats, and patterns
- Documentation: Provide comprehensive, up-to-date API documentation
- Versioning: Plan for evolution with clear versioning strategies
- Error Handling: Implement consistent, informative error responses
- Security: Build security into every layer of the API
- Performance: Design for scale and efficiency from the start
- Backward Compatibility: Minimize breaking changes and provide migration paths
- Testing: Implement comprehensive testing including contract testing
- Monitoring: Add observability for API usage and performance
- Developer Experience: Prioritize ease of use and clear documentation
Common Anti-Patterns to Avoid
- 1. Verb-based URLs: Use nouns for resources, not actions
- Inconsistent Response Formats: Maintain standard response structures
- Over-nesting: Avoid deeply nested resource hierarchies
- Ignoring HTTP Status Codes: Use appropriate status codes for different scenarios
- Poor Error Messages: Provide actionable, specific error information
- Missing Pagination: Always paginate list endpoints
- No Versioning Strategy: Plan for API evolution from day one
- Exposing Internal Structure: Design APIs for external consumption, not internal convenience
- Missing Rate Limiting: Protect your API from abuse and overload
- Inadequate Testing: Test all aspects including error cases and edge conditions
Conclusion
The API Design Reviewer skill provides a comprehensive framework for building, reviewing, and maintaining high-quality REST APIs. By following these guidelines and using the provided tools, development teams can create APIs that are consistent, well-documented, secure, and maintainable.
Regular use of the linting, breaking change detection, and scoring tools ensures continuous improvement and helps maintain API quality throughout the development lifecycle.
API 设计审查工具
层级: 强大
类别: 工程/架构
维护者: Claude 技能团队
概述
API 设计审查工具技能提供对 API 设计的全面分析和审查,重点关注 REST 约定、最佳实践和行业标准。该技能通过自动化的代码检查、破坏性变更检测和设计评分卡,帮助工程团队构建一致、可维护且设计良好的 API。
核心能力
1. API 代码检查与约定分析
- - 资源命名约定:强制资源使用短横线命名法,字段使用驼峰命名法
- HTTP 方法使用:验证 GET、POST、PUT、PATCH、DELETE 的正确使用
- URL 结构:分析端点模式的一致性和 RESTful 设计
- 状态码合规性:确保使用适当的 HTTP 状态码
- 错误响应格式:验证一致的错误响应结构
- 文档覆盖率:检查缺失的描述和文档空白
2. 破坏性变更检测
- - 端点移除:检测已移除或弃用的端点
- 响应形状变化:识别响应结构的修改
- 字段移除:跟踪 API 响应中移除或重命名的字段
- 类型变更:捕获可能破坏客户端的字段类型修改
- 必填字段添加:标记可能破坏现有集成的新的必填字段
- 状态码变更:检测预期状态码的变化
3. API 设计评分与评估
- - 一致性分析(30%):评估命名约定、响应模式和结构一致性
- 文档质量(20%):评估 API 文档的完整性和清晰度
- 安全实现(20%):审查身份验证、授权和安全标头
- 可用性设计(15%):分析易用性、可发现性和开发者体验
- 性能模式(15%):评估缓存、分页和效率模式
REST 设计原则
资源命名约定
✅ 良好示例:
- - /api/v1/users
- /api/v1/user-profiles
- /api/v1/orders/123/line-items
❌ 错误示例:
- - /api/v1/getUsers
- /api/v1/user_profiles
- /api/v1/orders/123/lineItems
HTTP 方法使用
- - GET:检索资源(安全、幂等)
- POST:创建新资源(非幂等)
- PUT:替换整个资源(幂等)
- PATCH:部分资源更新(不一定幂等)
- DELETE:移除资源(幂等)
URL 结构最佳实践
集合资源:/api/v1/users
单个资源:/api/v1/users/123
嵌套资源:/api/v1/users/123/orders
操作:/api/v1/users/123/activate (POST)
过滤:/api/v1/users?status=active&role=admin
版本控制策略
1. URL 版本控制(推荐)
/api/v1/users
/api/v2/users
优点:清晰、明确、易于路由
缺点:URL 膨胀、缓存复杂性
2. 标头版本控制
GET /api/users
Accept: application/vnd.api+json;version=1
优点:URL 简洁、内容协商
缺点:可见性较低、手动测试较难
3. 媒体类型版本控制
GET /api/users
Accept: application/vnd.myapi.v1+json
优点:RESTful、支持多种表示形式
缺点:复杂、实现较难
4. 查询参数版本控制
/api/users?version=1
优点:实现简单
缺点:非 RESTful、可能被忽略
分页模式
基于偏移量的分页
json
{
data: [...],
pagination: {
offset: 20,
limit: 10,
total: 150,
hasMore: true
}
}
基于游标的分页
json
{
data: [...],
pagination: {
nextCursor: eyJpZCI6MTIzfQ==,
hasMore: true
}
}
基于页面的分页
json
{
data: [...],
pagination: {
page: 3,
pageSize: 10,
totalPages: 15,
totalItems: 150
}
}
错误响应格式
标准错误结构
json
{
error: {
code: VALIDATION_ERROR,
message: 请求包含无效参数,
details: [
{
field: email,
code: INVALID_FORMAT,
message: 电子邮件地址无效
}
],
requestId: req-123456,
timestamp: 2024-02-16T13:00:00Z
}
}
HTTP 状态码使用
- - 400 错误请求:请求语法或参数无效
- 401 未授权:需要身份验证
- 403 禁止访问:访问被拒绝(已认证但未授权)
- 404 未找到:资源未找到
- 409 冲突:资源冲突(重复、版本不匹配)
- 422 不可处理的实体:语法有效但语义错误
- 429 请求过多:超出速率限制
- 500 内部服务器错误:意外的服务器错误
身份验证与授权模式
令牌身份验证
Authorization: Bearer
API 密钥身份验证
X-API-Key:
Authorization: Api-Key
OAuth 2.0 流程
Authorization: Bearer
基于角色的访问控制(RBAC)
json
{
user: {
id: 123,
roles: [admin, editor],
permissions: [read:users, write:orders]
}
}
速率限制实现
标头
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1640995200
超出限制时的响应
json
{
error: {
code: RATE
LIMITEXCEEDED,
message: 请求过多,
retryAfter: 3600
}
}
HATEOAS(超媒体作为应用状态引擎)
示例实现
json
{
id: 123,
name: 张三,
email: zhangsan@example.com,
_links: {
self: { href: /api/v1/users/123 },
orders: { href: /api/v1/users/123/orders },
profile: { href: /api/v1/users/123/profile },
deactivate: {
href: /api/v1/users/123/deactivate,
method: POST
}
}
}
幂等性
幂等方法
- - GET:始终安全且幂等
- PUT:应为幂等(替换整个资源)
- DELETE:应为幂等(相同结果)
- PATCH:可能幂等也可能不幂等
幂等键
POST /api/v1/payments
Idempotency-Key: 123e4567-e89b-12d3-a456-426614174000
向后兼容性指南
安全变更(非破坏性)
- - 向请求添加可选字段
- 向响应添加字段
- 添加新端点
- 将必填字段改为可选
- 添加新的枚举值(需优雅处理)
破坏性变更(需要版本升级)
- - 从响应中移除字段
- 将可选字段改为必填
- 更改字段类型
- 移除端点
- 更改 URL 结构
- 修改错误响应格式
OpenAPI/Swagger 验证
必需组件
- - API 信息:标题、描述、版本
- 服务器信息:基础 URL 和描述
- 路径定义:所有端点及其方法
- 参数定义:查询、路径、标头参数
- 请求/响应模式:完整的数据模型
- 安全定义:身份验证方案
- 错误响应:标准错误格式
最佳实践
- - 使用一致的命名约定
- 为所有组件提供详细描述
- 为复杂对象包含示例
- 定义可复用的组件和模式
- 根据 OpenAPI 规范进行验证
性能考虑
缓存策略
Cache-Control: public, max-age=3600
ETag: 123