如何在OpenAPI 2.0(Swagger 2.0)中定义自定义头?

5

我在定义OpenAPI(Swagger)文档的自定义请求头时遇到了问题。我已经查看了文档https://swagger.io/docs/specification/describing-parameters/#header-parameters,但我无法让它起作用。

以下是我的示例,其中包含一个具有请求体的POST请求。我还希望它具有像第二个代码片段中的自定义头,但那样不合法。

这是可以的:

 /search:
    post:
      tags:
        - Domain
      summary: Search for domains
      description: Returns a domain if it was found.
      produces:
        - application/json
      parameters:
        - in: body
          name: body
          description: Array of Domain Names
          required: true
          schema:
            $ref: '#/definitions/DomainNames'

这是不行的:

  /search:
    post:
      tags:
        - Domain
      summary: Search for domains
      description: Returns a domain if it was found.
      produces:
        - application/json
      parameters:
       - in: header
          name: X-Request-ID
          schema:
            type: string
            format: uuid
          required: true
        - in: body
          name: body
          description: Array of Domain Names
          required: true
          schema:
            $ref: '#/definitions/DomainNames'

-in: header行中,我遇到了以下错误:

paths['/search'].post.parameters[0].in的架构错误
应该等于允许的值之一
allowedValues:body、header、formData、query、path
跳转到第37行

paths['/search'].post.parameters[0]的架构错误
不应该有附加属性
additionalProperty:schema、in、name
跳转到第37行

我错过了什么?这个头部显示在呈现的Swagger UI中,但我无法“保存”它,因为它无效。

1个回答

4
你提供的指南是针对 OpenAPI 3.0 的(如该页面顶部所示)。相应的OpenAPI 2.0 指南在此处:描述参数
在 OpenAPI 2.0 中,path/header/query/form 参数不使用 schema,而是直接使用 type 关键字。
另外,在你的示例中,- in: header 行缩进不够,需要在前面再加一个空格以与其他行对齐。
以下是正确版本:
      parameters:
        - in: header     # <----
          name: X-Request-ID
          type: string   # <----
          format: uuid   # <----
          required: true

我们无法在OpenAPI2.0中提供自定义的JSON(对象)类型信息吗?此尝试无法编译 - Anu
1
@Anu 在 OpenAPI 2.0 中,您只能在请求正文中发送 JSON(和一般对象)--参见 Post a JSON body with OpenAPI 2.0。OpenAPI 3.0 添加了对参数中对象的支持。 - Helen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接