查询和/或正文中的 Swagger 参数

标签 swagger swagger-codegen

我们的 API 有这样的端点,支持来自 query 的参数。来自 body同时,通过合并这两组参数。

例如:

/foo?param1=value1
body: {
    param2=value2
}

结果参数集将包含两个,param1param2 .

此端点可用作:
/foo?param1=value1&param2=value2

或者
/foo
body: {
    param1=value1,
    param2=value2
}

有没有办法在 Swagger 中指定这种“二元性”?

UPD
我想我应该将参数定义为两者:bodyquery
in:
  - body
  - query

最佳答案

您需要定义查询参数和正文参数,但将它们都标记为可选。使用操作description解释客户端可以在查询字符串或正文中发送参数。

swagger: '2.0'
...
paths:
  /foo:
    post:
      consumes:
        - application/json
      parameters:
        - in: query
          name: param1
          type: string
          required: false
        - in: query
          name: param2
          type: string
          required: false
        - in: body
          name: body
          required: false
          schema:
            type: object
            properties:
              param1:
                type: string
              param2:
                type: string

使用 OpenAPI 3.0,它更优雅一点,您可以重用相同的 schema对于查询字符串和请求正文:

openapi: 3.0.0
...
paths:
  /foo:
    post:
      parameters:
        # This expands into ?param1=value1&param2=value2&...
        - in: query
          name: parameters
          required: false
          schema:
            $ref: '#/components/schemas/Parameters'
          style: form
          explode: true
      requestBody:
        required: false
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Parameters'
      responses:
        '200':
          description: OK

components:
  schemas:
    Parameters:
      type: object
      properties:
        param1:
          type: string
        param2:
          type: string

Swagger UI 用户注意事项:从 UI v. 3.11.0 开始,似乎还不支持将对象序列化为查询字符串。

关于查询和/或正文中的 Swagger 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49013630/

相关文章:

java - 如何让maven在编译时只考虑一组重复文件中的一个?

json - 为同一项目中的多个 swagger 生成代码

rest - 如何在 swagger 中为可变路径参数和特定路径参数定义 2 个不同的端点

spring - 使用开放 API 配置设置全局参数?

c# - 我可以使用 Swashbuckle 从 Blazor 项目 c# 生成 Swagger UI

java - swagger-codegen 客户端 : How to include jackson annotations on models

kotlin - 为 Kotlin Swagger

Swagger + Nest.js 不会删除空的 DTO 和模型

Swagger 3.0.0 代码生成失败 java.lang.RuntimeException : missing swagger input or config

scala - 在 sbt compile 上获取 Unresolved 依赖关系