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

OpenAPI 3.0响应Schema使用路径变量的实现及解析错误排查

问题描述

我有一个遗留REST端点,希望用OpenAPI 3.0对其进行定义。该端点使用路径变量,路径为action/{action}s/,且响应JSON Schema中会用到此路径变量,示例响应如下:

{
  "name": "someName",
  "{action}": "someActionName",
  "{action}Id": 5
}

我在OpenAPI官方指南中没找到相关说明,请问是否可以生成符合该需求的OpenAPI 3.0规范?若可行,示例应该怎么写?

我尝试编写了如下规范,但在editor.swagger.io中第31行({action}Id:所在行)出现解析错误:

openapi: 3.0.0
info:
  title: My API
  version: 1.0.0
paths:
  /myaction/{action}s:
    get:
      summary: Get information for a specific action
      operationId: getActionInfo
      parameters:
        - name: action
          in: path
          required: true
          description: The name of the action
          schema:
            type: string
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  name:
                    type: string
                    description: The name of the response object
                  {action}:
                    type: string
                    description: The name of the action
                  {action}Id:
                    type: integer
                    description: The ID of the action
                required:
                  - name
                  - {action}
                  - {action}Id
解决方案

可以实现这个需求,你的YAML代码出现解析错误,是因为字段名包含{、}这类YAML特殊字符,必须用双引号把这些字段名包裹起来,否则解析器会把它们当成YAML的特殊语法处理。

修正后的完整OpenAPI规范如下:

openapi: 3.0.0
info:
  title: My API
  version: 1.0.0
paths:
  /myaction/{action}s:
    get:
      summary: 获取指定动作的信息
      operationId: getActionInfo
      parameters:
        - name: action
          in: path
          required: true
          description: 动作名称
          schema:
            type: string
      responses:
        '200':
          description: 成功响应
          content:
            application/json:
              schema:
                type: object
                properties:
                  name:
                    type: string
                    description: 响应对象名称
                  "{action}":
                    type: string
                    description: 动作名称
                  "{action}Id":
                    type: integer
                    description: 动作ID
                required:
                  - name
                  - "{action}"
                  - "{action}Id"

需要注意的点:

  • 所有包含{和}的字段名(比如{action}、{action}Id)都要用双引号包裹,确保YAML解析器将其视为普通字符串键名。
  • 这个写法完全符合OpenAPI 3.0规范,因为JSON Schema允许动态命名的属性,只要在YAML中正确转义特殊字符即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 15:32:10