api-design-reviewer

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

API Design Reviewer

API设计评审器

Tier: POWERFUL
Category: Engineering / Architecture
Maintainer: Claude Skills Team
级别: 强大级
分类: 工程/架构
维护者: Claude技能团队

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规范、最佳实践及行业标准。该技能通过自动化检查、破坏性变更检测和设计评分卡,帮助工程团队构建一致性强、易于维护且设计优良的API。

Core Capabilities

核心功能

1. API Linting and Convention Analysis

1. API规范检查与约定分析

  • 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方法使用:验证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/lineItems

HTTP Method Usage

HTTP方法使用

  • 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=admin

Versioning Strategies

版本控制策略

1. URL Versioning (Recommended)

1. URL版本控制(推荐)

/api/v1/users
/api/v2/users
Pros: Clear, explicit, easy to route
Cons: URL proliferation, caching complexity
/api/v1/users
/api/v2/users
优点: 清晰明确,易于路由
缺点: URL膨胀,缓存复杂度高

2. Header Versioning

2. 请求头版本控制

GET /api/users
Accept: application/vnd.api+json;version=1
Pros: Clean URLs, content negotiation
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+json
Pros: RESTful, supports multiple representations
Cons: Complex, harder to implement
GET /api/users
Accept: application/vnd.myapi.v1+json
优点: 符合REST规范,支持多种表示形式
缺点: 复杂度高,实现难度大

4. Query Parameter Versioning

4. 查询参数版本控制

/api/users?version=1
Pros: Simple to implement
Cons: Not RESTful, can be ignored
/api/users?version=1
优点: 实现简单
缺点: 不符合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": "请求包含无效参数",
    "details": [
      {
        "field": "email",
        "code": "INVALID_FORMAT",
        "message": "邮箱地址无效"
      }
    ],
    "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令牌认证

Authorization: Bearer <token>
Authorization: Bearer <token>

API Key Authentication

API密钥认证

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: 1640995200
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1640995200

Response on Limit Exceeded

超限响应

json
{
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Too many requests",
    "retryAfter": 3600
  }
}
json
{
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "请求过于频繁",
    "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-426614174000
POST /api/v1/payments
Idempotency-Key: 123e4567-e89b-12d3-a456-426614174000

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
  • 移除响应中的字段
  • 将可选字段设为必填
  • 修改字段类型
  • 移除端点
  • 修改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 GMT
Cache-Control: public, max-age=3600
ETag: "123456789"
Last-Modified: Wed, 21 Oct 2015 07:28:00 GMT

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
  • 使用恰当的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.json
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.json

Pre-commit Hooks

提交前钩子

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
fi
bash
#!/bin/bash
python engineering/api-design-reviewer/scripts/api_linter.py api/openapi.json
if [ $? -ne 0 ]; then
  echo "API规范检查失败,请修复问题后再提交。"
  exit 1
fi

Best Practices Summary

最佳实践总结

  1. Consistency First: Maintain consistent naming, response formats, and patterns
  2. Documentation: Provide comprehensive, up-to-date API documentation
  3. Versioning: Plan for evolution with clear versioning strategies
  4. Error Handling: Implement consistent, informative error responses
  5. Security: Build security into every layer of the API
  6. Performance: Design for scale and efficiency from the start
  7. Backward Compatibility: Minimize breaking changes and provide migration paths
  8. Testing: Implement comprehensive testing including contract testing
  9. Monitoring: Add observability for API usage and performance
  10. Developer Experience: Prioritize ease of use and clear documentation
  1. 一致性优先: 保持命名、响应格式与模式的一致性
  2. 文档: 提供全面且及时更新的API文档
  3. 版本控制: 规划清晰的版本控制策略以支持API演进
  4. 错误处理: 实现一致且信息丰富的错误响应
  5. 安全: 在API的每一层都融入安全设计
  6. 性能: 从设计初期就考虑扩展性与效率
  7. 向后兼容性: 尽量减少破坏性变更并提供迁移路径
  8. 测试: 实现全面测试,包括契约测试
  9. 监控: 添加API使用情况与性能的可观测性
  10. 开发者体验: 优先考虑易用性与清晰的文档

Common Anti-Patterns to Avoid

需避免的常见反模式

  1. Verb-based URLs: Use nouns for resources, not actions
  2. Inconsistent Response Formats: Maintain standard response structures
  3. Over-nesting: Avoid deeply nested resource hierarchies
  4. Ignoring HTTP Status Codes: Use appropriate status codes for different scenarios
  5. Poor Error Messages: Provide actionable, specific error information
  6. Missing Pagination: Always paginate list endpoints
  7. No Versioning Strategy: Plan for API evolution from day one
  8. Exposing Internal Structure: Design APIs for external consumption, not internal convenience
  9. Missing Rate Limiting: Protect your API from abuse and overload
  10. Inadequate Testing: Test all aspects including error cases and edge conditions
  1. 动词型URL: 资源使用名词而非动词
  2. 不一致的响应格式: 保持标准响应结构
  3. 过度嵌套: 避免深度嵌套的资源层级
  4. 忽略HTTP状态码: 根据不同场景使用恰当的状态码
  5. 糟糕的错误信息: 提供可操作的具体错误信息
  6. 缺失分页: 列表端点务必实现分页
  7. 无版本控制策略: 从第一天就规划API演进方案
  8. 暴露内部结构: 为外部使用设计API,而非仅考虑内部便利
  9. 缺失限流: 保护API免受滥用与过载
  10. 测试不足: 测试所有场景,包括错误情况与边缘案例

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。
定期使用规范检查、破坏性变更检测与评分工具,可确保持续改进,并在整个开发生命周期中维持API质量。