---
name: api-contract-rules
type: review_rule
when: '代码审查, review, 接口契约检查, API规范检查'
scope:
  - backend
products:
  - '*'
id: ka-review-rule-接口契约审查规则
asset_kind: review_rule
lifecycle_status: active
authority: supporting
routes:
  - code_change
primary_triggers:
  - 接口契约审查规则
secondary_triggers: []
negative_triggers: []
priority: P1
specificity: 5
required_evidence:
  - execution_evidence
version: 1.0.0
last_reviewed: '2026-05-22'
migration_note: 知识资产标准化迁移
status: active
---

## API-01: Controller 返回 Entity 而非 DTO
pattern: "ResponseEntity<Entity>|ResponseEntity<\\s*$"
severity: warning
scope: backend
description: 禁止直接返回数据库 Entity，必须通过 DTO/VO 转换，防止敏感字段泄漏和结构耦合

## API-02: 缺少 @Transactional 的写操作
pattern: "@(PostMapping|PutMapping|DeleteMapping|PatchMapping)"
severity: warning
scope: backend
description: 写操作 Service 方法必须标注 @Transactional(rollbackFor = Exception.class)

## API-03: 接口缺少权限注解
pattern: "@(PostMapping|PutMapping|DeleteMapping)"
severity: critical
scope: backend
description: 写接口必须有 @PreAuthorize 或 @Secured 注解，禁止裸露写操作

## API-04: 硬编码分页参数
pattern: "LIMIT\\s+\\d+|pageSize\\s*=\\s*\\d{4,}"
severity: warning
scope: backend
description: 分页参数禁止硬编码大数字，pageSize 上限不超过 100

## API-05: 缺少参数校验注解
pattern: "@RequestBody\\s+\\w+\\s+\\w+"
severity: info
scope: backend
description: @RequestBody 参数应搭配 @Valid 或 @Validated 注解触发校验

## API-06: 接口路径不符合 RESTful 规范
pattern: "@(Get|Post|Put|Delete)Mapping.*(/get|/query|/add|/update|/delete|/list)"
severity: info
scope: backend
description: 接口路径应使用资源名词 + HTTP 方法语义，避免 /getUser、/deleteOrder 等动词路径

## API-07: 接口缺少统一响应包装
pattern: /ResponseEntity<\s*(?!ApiResult|Result|R<)/
severity: warning
scope: backend
description: 接口返回值必须使用统一响应包装（如 Result<T>），禁止直接返回裸数据或 ResponseEntity

## API-08: 分页接口返回非标准结构
pattern: /Page(?:Info|able)|PageRequest/
severity: info
scope: backend
description: 分页接口必须返回标准结构（total、list、pageNum、pageSize），禁止自定义分页格式

## API-09: 缺少接口版本号
pattern: /@(?:Get|Post|Put|Delete)Mapping\s*\(\s*"\/(?!v\d)/
severity: info
scope: backend
description: API 路径应包含版本号前缀（如 /api/v1/），便于后续接口演进和兼容

## API-10: 接口缺少 Swagger/OpenAPI 文档注解
pattern: /@(?:Get|Post|Put|Delete)Mapping\s*\(/
severity: info
scope: backend
description: 接口必须添加 @Operation/@Api 注解，保证 API 文档自动生成
