You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否为返回ResponseBodyEmitter的Spring Rest Controller生成正确OpenAPI YAML?

为返回ResponseBodyEmitter的RestController生成OpenAPI YAML的方法

对于返回ResponseBodyEmitter的流式接口,OpenAPI规范支持通过配置流式响应的元数据来生成正确的YAML文件——因为自动生成工具通常无法直接识别ResponseBodyEmitter的返回逻辑,需要手动补充或增强配置。

核心配置要点

  • 指定响应媒体类型:根据接口实际发送的内容格式(示例中是纯文本,对应text/plain;如果是JSON对象则用application/json)设置响应的content类型。
  • 标记流式属性:在媒体类型的schema下添加stream: true,明确这是持续输出的流式响应。
  • 补充接口说明:在OpenAPI配置里标注接口的流式特性,帮助使用者理解返回逻辑。

示例OpenAPI YAML片段

纯文本流场景

paths:
  /streaming:
    get:
      summary: 获取流式文本数据
      description: 通过ResponseBodyEmitter持续返回文本内容
      responses:
        '200':
          description: 成功返回流式文本
          content:
            text/plain:
              schema:
                type: string
                stream: true

JSON对象流场景

如果接口每次发送的是SomeDto类型的JSON对象,配置如下:

paths:
  /streaming:
    get:
      summary: 获取流式JSON数据
      description: 通过ResponseBodyEmitter持续返回JSON对象
      responses:
        '200':
          description: 成功返回流式JSON对象
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SomeDto'
                stream: true
components:
  schemas:
    SomeDto:
      type: object
      properties:
        id:
          type: integer
        content:
          type: string

自动生成工具适配(以SpringDoc为例)

如果使用SpringDoc这类自动生成工具,可通过注解补充元数据:

@GetMapping(path = "/streaming", produces = MediaType.TEXT_PLAIN_VALUE)
@ApiResponse(responseCode = "200", content = @Content(
    mediaType = MediaType.TEXT_PLAIN_VALUE,
    schema = @Schema(type = "string", stream = true)
))
public ResponseBodyEmitter getSomeStream() {
   // 方法实现逻辑
}

添加上述注解后,SpringDoc会自动生成包含流式响应定义的OpenAPI YAML文件。

内容的提问来源于stack exchange,提问作者Anton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 13:52:41