【问题标题】:How to make Swagger UI accepts request body with optional field如何使 Swagger UI 接受带有可选字段的请求正文
【发布时间】:2021-11-26 05:43:20
【问题描述】:

好吧,标题很容易理解,但要详细说明:

我有一个用 TypeScript 编写的 expressjs 应用程序。应用收到一个请求,其中的 JSON 正文是这样的:

{
    name: "name",
    description: "description",
    github: "github",
    logo: "logo",
    app: "app"
}

但问题是:app 属性是可选的,因为只有在声明了请求的情况下,我才会将带有该属性的对象插入到数据库中。

我想知道是否有可能让 Swagger 接受那个可选的东西,如果可以,该怎么做?

编辑: 根据@Anatoly 的要求,这是招摇路线定义:

post: {
    summary: 'Create a new project',
    tags: ['projects'],
    requestBody: {
        content: {
            'application/json': {
                schema: {
                    $ref: '#/components/schemas/Project'
                }
            }
        }
    }
},
components: {
    schemas: {
        Project: {
            type: 'object',
            properties: {
                name: {
                    type: 'string'
                },
                description: {
                    type: 'string'
                },
                github: {
                    type: 'string'
                },
                logo: {
                    type: 'string'
                },
                app: {
                    type: 'string'
                }
            }
        }
    }
}

【问题讨论】:

标签: node.js json rest express swagger


【解决方案1】:

除了路径参数之外的所有参数都是可选的,除非它们的 required 属性为 true

app:
  type:string
  required:true

请参阅标题 Required and Optional Parameters https://swagger.io/docs/specification/describing-parameters/

【讨论】: