Hyperf 中生成规范批量修改接口文档需用 @Patch/@Put 注解定义路径,RequestBody 用 array schema 描述 ID+更新字段结构,验证注解同步校验规则,响应文档明确汇总结果与错误码。

Hyperf 框架中生成规范的批量修改接口文档,关键在于准确表达「批量」语义、明确请求体结构、标注字段约束,并让 Swagger 能自动识别和渲染为标准 OpenAPI 格式。不需要手写 JSON,靠注解就能实现。
用 @Put / @Patch 注解定义批量更新行为
RESTful 规范中,批量修改推荐使用 PATCH(部分更新)或 PUT(全量替换),不建议用 POST。Hyperf Swagger 支持通过方法级注解声明 HTTP 方法和路径:
#[SA\Patch(path: '/users/batch', summary: '批量更新用户信息')]#[SA\Put(path: '/products/batch', summary: '全量替换商品列表')]
注意:路径应体现资源集合与操作意图,如 /users/batch 或 /orders/status,避免写成 /updateBatch 这类动词化路径。
用 RequestBody + Schema 描述批量数据结构
批量接口的核心是请求体(RequestBody)——它不是单个对象,而是一个数组,每个元素含 ID 和待更新字段。需用 schema 明确嵌套结构:
- 外层设
type: 'array',items指向一个内联 Schema - 内层 Schema 定义每个条目的必填字段(如
id)、可选更新字段(如status、remark)及类型 - 用
required数组限定哪些字段在每条记录中必须提供
示例片段:
#[SA\RequestBody(
description: '批量更新用户状态',
content: [
new SA\MediaType(
mediaType: 'application/json',
schema: new SA\Schema(
type: 'array',
items: new SA\Schema(
required: ['id'],
properties: [
new SA\Property(property: 'id', type: 'integer', description: '用户ID'),
new SA\Property(property: 'status', type: 'string', enum: ['active', 'inactive'], description: '新状态'),
new SA\Property(property: 'remark', type: 'string', nullable: true),
]
)
)
)
]
)]
为每个字段添加校验注解并同步到文档
Hyperf 原生验证器(hyperf/validation)与 Swagger 注解可联动。只要在 Controller 方法参数中使用带 @RequestValidation 的 DTO 类,或直接在方法签名中加 #[Validate],验证规则就会反映在文档的 schema 中:
-
#[Validate(required: true, integer: true)] public int $id→ 文档中标记为required且类型为integer -
#[Validate(in: 'active,inactive')] public string $status→ 自动生成enum列表 -
#[Validate(max: 200)] public ?string $remark→ 渲染出maxLength: 200
这样既保证运行时校验,又让前端/测试人员一眼看清字段边界。
补充成功响应与错误码说明
批量操作常见返回模式是「汇总结果」,例如:
- 总处理数、成功数、失败数
- 失败详情列表(含 ID 和错误原因)
用 #[SA\Response] 描述 200 成功响应,并配一个清晰的 Schema:
#[SA\Response(
response: 200,
description: '批量更新结果',
content: new SA\MediaType(
mediaType: 'application/json',
schema: new SA\Schema(
properties: [
new SA\Property(property: 'total', type: 'integer'),
new SA\Property(property: 'success_count', type: 'integer'),
new SA\Property(property: 'failed_count', type: 'integer'),
new SA\Property(
property: 'failures',
type: 'array',
items: new SA\Schema(
properties: [
new SA\Property(property: 'id', type: 'integer'),
new SA\Property(property: 'message', type: 'string'),
]
)
),
]
)
)
)]
同时别忘了标注常见错误,比如 400(参数格式错误)、422(校验失败)、404(部分 ID 不存在)——这些都会出现在 Swagger UI 的「Responses」区域,提升协作效率。


















