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

能否在OpenAPI的paths响应中直接定义端点的固定返回内容?

OpenAPI中定义固定响应的方法

是的,OpenAPI规范完全支持直接定义这类固定响应,常用的实现方式有两种:

  • 使用example字段:这就是你给出的示例里的方式,通过在schema中添加example字段,可以直接指定接口返回的固定示例值,清晰展示接口的实际返回内容,非常适合/ping这种返回固定字符串的场景。示例代码如下:
paths:
  /ping:
    get:
      responses:
        '200':
          description: OK
          content:
            text/plain:
              schema:
                type: string
                example: pong
  • 使用const字段:如果需要强制接口返回值必须是某个固定值(而不只是提供示例),可以用const字段来约束schema,明确限定返回内容只能是指定值。示例代码如下:
paths:
  /ping:
    get:
      responses:
        '200':
          description: OK
          content:
            text/plain:
              schema:
                type: string
                const: pong

如果需要展示多个不同的响应示例,还可以使用examples(复数)字段,但对于固定响应的场景,example或const就足够满足需求了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 07:57:05