api-design-reviewer
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAPI Design Reviewer
API设计评审工具
Tier: POWERFUL
Category: Engineering / Architecture
Maintainer: Claude Skills Team
等级:POWERFUL
分类:工程/架构
维护者: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.
API设计评审工具可对API设计进行全面分析和评审,重点关注REST规范、最佳实践和行业标准。该工具通过自动化lint检查、破坏性变更检测和设计评分卡,帮助工程团队构建一致性高、可维护性强、设计精良的API。
Core Capabilities
核心功能
1. API Linting and Convention Analysis
1. API Lint检查与规范分析
- 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
- 资源命名规范:强制要求资源使用kebab-case命名、字段使用camelCase命名
- HTTP Method使用规范:验证GET、POST、PUT、PATCH、DELETE的使用是否合规
- URL结构检查:分析端点模式的一致性和RESTful设计合理性
- 状态码合规性:确保使用合适的HTTP状态码
- 错误响应格式检查:验证错误响应结构的一致性
- 文档覆盖度检查:排查缺失的描述和文档缺口
2. Breaking Change Detection
2. 破坏性变更检测
- 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
- 端点移除检测:检测已移除或已弃用的端点
- 响应结构变更检测:识别响应结构的修改
- 字段移除检测:追踪API响应中已移除或重命名的字段
- 类型变更检测:捕获可能导致客户端崩溃的字段类型修改
- 必填字段新增检测:标记可能破坏现有集成的新增必填字段
- 状态码变更检测:检测预期状态码的变更
3. API Design Scoring and Assessment
3. API设计评分与评估
- 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
- 一致性分析(30%):评估命名规范、响应模式和结构一致性
- 文档质量(20%):评估API文档的完整性和清晰度
- 安全实现(20%):评审身份认证、授权和安全头配置
- 易用性设计(15%):分析易用性、可发现性和开发者体验
- 性能模式(15%):评估缓存、分页和效率模式
REST Design Principles
REST设计原则
Resource Naming Conventions
资源命名规范
✅ Good Examples:
- /api/v1/users
- /api/v1/user-profiles
- /api/v1/orders/123/line-items
❌ Bad Examples:
- /api/v1/getUsers
- /api/v1/user_profiles
- /api/v1/orders/123/lineItems✅ 正确示例:
- /api/v1/users
- /api/v1/user-profiles
- /api/v1/orders/123/line-items
❌ 错误示例:
- /api/v1/getUsers
- /api/v1/user_profiles
- /api/v1/orders/123/lineItemsHTTP Method Usage
HTTP Method使用规范
- 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)
- GET:获取资源(安全、幂等)
- POST:创建新资源(非幂等)
- PUT:替换完整资源(幂等)
- PATCH:部分更新资源(不一定幂等)
- DELETE:移除资源(幂等)
URL Structure Best Practices
URL结构最佳实践
Collection Resources: /api/v1/users
Individual Resources: /api/v1/users/123
Nested Resources: /api/v1/users/123/orders
Actions: /api/v1/users/123/activate (POST)
Filtering: /api/v1/users?status=active&role=admin集合资源: /api/v1/users
单个资源: /api/v1/users/123
嵌套资源: /api/v1/users/123/orders
动作: /api/v1/users/123/activate (POST)
过滤: /api/v1/users?status=active&role=adminVersioning Strategies
版本管理策略
1. URL Versioning (Recommended)
1. URL版本管理(推荐)
/api/v1/users
/api/v2/usersPros: Clear, explicit, easy to route
Cons: URL proliferation, caching complexity
Cons: URL proliferation, caching complexity
/api/v1/users
/api/v2/users优点:清晰明确、易于路由
缺点:URL数量激增、缓存复杂度高
缺点:URL数量激增、缓存复杂度高
2. Header Versioning
2. 请求头版本管理
GET /api/users
Accept: application/vnd.api+json;version=1Pros: Clean URLs, content negotiation
Cons: Less visible, harder to test manually
Cons: Less visible, harder to test manually
GET /api/users
Accept: application/vnd.api+json;version=1优点:URL简洁、支持内容协商
缺点:可见性低、手动测试难度大
缺点:可见性低、手动测试难度大
3. Media Type Versioning
3. 媒体类型版本管理
GET /api/users
Accept: application/vnd.myapi.v1+jsonPros: RESTful, supports multiple representations
Cons: Complex, harder to implement
Cons: Complex, harder to implement
GET /api/users
Accept: application/vnd.myapi.v1+json优点:符合REST规范、支持多种表示形式
缺点:复杂度高、实现难度大
缺点:复杂度高、实现难度大
4. Query Parameter Versioning
4. 查询参数版本管理
/api/users?version=1Pros: Simple to implement
Cons: Not RESTful, can be ignored
Cons: Not RESTful, can be ignored
/api/users?version=1优点:实现简单
缺点:不符合REST规范、容易被忽略
缺点:不符合REST规范、容易被忽略
Pagination Patterns
分页模式
Offset-Based Pagination
偏移量分页
json
{
"data": [...],
"pagination": {
"offset": 20,
"limit": 10,
"total": 150,
"hasMore": true
}
}json
{
"data": [...],
"pagination": {
"offset": 20,
"limit": 10,
"total": 150,
"hasMore": true
}
}Cursor-Based Pagination
游标分页
json
{
"data": [...],
"pagination": {
"nextCursor": "eyJpZCI6MTIzfQ==",
"hasMore": true
}
}json
{
"data": [...],
"pagination": {
"nextCursor": "eyJpZCI6MTIzfQ==",
"hasMore": true
}
}Page-Based Pagination
页码分页
json
{
"data": [...],
"pagination": {
"page": 3,
"pageSize": 10,
"totalPages": 15,
"totalItems": 150
}
}json
{
"data": [...],
"pagination": {
"page": 3,
"pageSize": 10,
"totalPages": 15,
"totalItems": 150
}
}Error Response Formats
错误响应格式
Standard Error Structure
标准错误结构
json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "The request contains invalid parameters",
"details": [
{
"field": "email",
"code": "INVALID_FORMAT",
"message": "Email address is not valid"
}
],
"requestId": "req-123456",
"timestamp": "2024-02-16T13:00:00Z"
}
}json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "The request contains invalid parameters",
"details": [
{
"field": "email",
"code": "INVALID_FORMAT",
"message": "Email address is not valid"
}
],
"requestId": "req-123456",
"timestamp": "2024-02-16T13:00:00Z"
}
}HTTP Status Code Usage
HTTP状态码使用规范
- 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
- 400 Bad Request:请求语法或参数无效
- 401 Unauthorized:需要身份认证
- 403 Forbidden:访问被拒绝(已认证但无权限)
- 404 Not Found:资源不存在
- 409 Conflict:资源冲突(重复、版本不匹配)
- 422 Unprocessable Entity:语法有效但语义错误
- 429 Too Many Requests:超出速率限制
- 500 Internal Server Error:意外服务端错误
Authentication and Authorization Patterns
身份认证与授权模式
Bearer Token Authentication
Bearer Token认证
Authorization: Bearer <token>Authorization: Bearer <token>API Key Authentication
API Key认证
X-API-Key: <api-key>
Authorization: Api-Key <api-key>X-API-Key: <api-key>
Authorization: Api-Key <api-key>OAuth 2.0 Flow
OAuth 2.0流程
Authorization: Bearer <oauth-access-token>Authorization: Bearer <oauth-access-token>Role-Based Access Control (RBAC)
基于角色的访问控制(RBAC)
json
{
"user": {
"id": "123",
"roles": ["admin", "editor"],
"permissions": ["read:users", "write:orders"]
}
}json
{
"user": {
"id": "123",
"roles": ["admin", "editor"],
"permissions": ["read:users", "write:orders"]
}
}Rate Limiting Implementation
速率限制实现
Headers
响应头
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1640995200X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1640995200Response on Limit Exceeded
超出限制后的响应
json
{
"error": {
"code": "RATE_LIMIT_EXCEEDED",
"message": "Too many requests",
"retryAfter": 3600
}
}json
{
"error": {
"code": "RATE_LIMIT_EXCEEDED",
"message": "Too many requests",
"retryAfter": 3600
}
}HATEOAS (Hypermedia as the Engine of Application State)
HATEOAS(超媒体作为应用状态引擎)
Example Implementation
实现示例
json
{
"id": "123",
"name": "John Doe",
"email": "john@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"
}
}
}json
{
"id": "123",
"name": "John Doe",
"email": "john@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"
}
}
}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
- GET:始终安全且幂等
- PUT:应当是幂等的(替换完整资源)
- DELETE:应当是幂等的(结果一致)
- PATCH:可能是幂等的,也可能不是
Idempotency Keys
幂等键
POST /api/v1/payments
Idempotency-Key: 123e4567-e89b-12d3-a456-426614174000POST /api/v1/payments
Idempotency-Key: 123e4567-e89b-12d3-a456-426614174000Backward 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
- 从响应中移除字段
- 将可选字段改为必填
- 变更字段类型
- 移除端点
- 修改URL结构
- 修改错误响应格式
OpenAPI/Swagger Validation
OpenAPI/Swagger验证
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
- API基本信息:标题、描述、版本
- 服务端信息:基础URL和描述
- 路径定义:所有端点及对应的请求方法
- 参数定义:查询参数、路径参数、请求头参数
- 请求/响应Schema:完整的数据模型
- 安全定义:身份认证方案
- 错误响应:标准错误格式
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
- 使用一致的命名规范
- 为所有组件提供详细描述
- 为复杂对象提供示例
- 定义可复用的组件和Schema
- 对照OpenAPI规范进行验证
Performance Considerations
性能注意事项
Caching Strategies
缓存策略
Cache-Control: public, max-age=3600
ETag: "123456789"
Last-Modified: Wed, 21 Oct 2015 07:28:00 GMTCache-Control: public, max-age=3600
ETag: "123456789"
Last-Modified: Wed, 21 Oct 2015 07:28:00 GMTEfficient Data Transfer
高效数据传输
- Use appropriate HTTP methods
- Implement field selection ()
?fields=id,name,email - Support compression (gzip)
- Implement efficient pagination
- Use ETags for conditional requests
- 使用合适的HTTP方法
- 实现字段选择功能()
?fields=id,name,email - 支持压缩(gzip)
- 实现高效分页
- 使用ETag实现条件请求
Resource Optimization
资源优化
- Avoid N+1 queries
- Implement batch operations
- Use async processing for heavy operations
- Support partial updates (PATCH)
- 避免N+1查询
- 实现批量操作
- 对重型操作使用异步处理
- 支持部分更新(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
- 全链路使用HTTPS
- 实现安全的令牌存储
- 支持令牌过期和刷新机制
- 使用高强度的身份认证机制
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
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
分析API规范是否符合REST规范和最佳实践。
功能:
- OpenAPI/Swagger规范验证
- 命名规范检查
- HTTP方法使用验证
- 错误格式一致性检查
- 文档完整性分析
breaking_change_detector.py
breaking_change_detector.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规范,识别破坏性变更。
功能:
- 端点对比
- Schema变更检测
- 字段移除/修改追踪
- 迁移指南生成
- 影响严重程度评估
api_scorecard.py
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
对API设计质量进行全面评分。
功能:
- 多维度评分
- 详细的改进建议
- 字母等级评估(A-F)
- 基准对比
- 进度追踪
Integration Examples
集成示例
CI/CD Integration
CI/CD集成
yaml
- name: API Linting
run: python scripts/api_linter.py openapi.json
- name: Breaking Change Detection
run: python scripts/breaking_change_detector.py openapi-v1.json openapi-v2.json
- name: API Scorecard
run: python scripts/api_scorecard.py openapi.jsonyaml
- name: API Linting
run: python scripts/api_linter.py openapi.json
- name: Breaking Change Detection
run: python scripts/breaking_change_detector.py openapi-v1.json openapi-v2.json
- name: API Scorecard
run: python scripts/api_scorecard.py openapi.jsonPre-commit Hooks
Pre-commit钩子
bash
#!/bin/bash
python engineering/api-design-reviewer/scripts/api_linter.py api/openapi.json
if [ $? -ne 0 ]; then
echo "API linting failed. Please fix the issues before committing."
exit 1
fibash
#!/bin/bash
python engineering/api-design-reviewer/scripts/api_linter.py api/openapi.json
if [ $? -ne 0 ]; then
echo "API linting failed. Please fix the issues before committing."
exit 1
fiBest Practices Summary
最佳实践总结
- 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
- 一致性优先:保持命名、响应格式和模式的一致性
- 文档完整:提供全面、及时更新的API文档
- 版本管理:通过清晰的版本策略为迭代做准备
- 错误处理:实现一致、信息明确的错误响应
- 安全防护:在API的每一层都内置安全能力
- 性能设计:从一开始就面向扩展性和效率进行设计
- 向后兼容:尽量减少破坏性变更,并提供迁移路径
- 全面测试:实现包括契约测试在内的全面测试体系
- 可观测性:添加API使用情况和性能的监控能力
- 开发者体验:优先保障易用性和清晰的文档
Common Anti-Patterns to Avoid
需要避免的常见反模式
- 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
- 基于动词的URL:资源使用名词而非动作命名
- 不一致的响应格式:保持标准的响应结构
- 过度嵌套:避免层级过深的资源结构
- 忽略HTTP状态码:不同场景使用合适的状态码
- 错误信息不清晰:提供可执行、具体的错误信息
- 缺失分页:所有列表端点都需要支持分页
- 无版本策略:从第一天就为API迭代做规划
- 暴露内部结构:API面向外部使用场景设计,而非内部便利
- 缺失速率限制:保护API免受滥用和过载
- 测试不充分:测试所有场景,包括错误 case和边界条件
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设计评审工具为构建、评审和维护高质量REST API提供了全面的框架。遵循这些指南并使用提供的工具,开发团队可以构建出一致性高、文档完善、安全且可维护的API。
定期使用lint检查、破坏性变更检测和评分工具,可以确保持续改进,在整个开发生命周期中维持API质量。