如何在同一对象的 Open API 请求和响应中设置不同的必填字段?

How to have different required fields in Open API Request and Response for same Object?

我使用的是 openapi 3.0.3 版本,我们有 scanario,我们不想让一个字段成为 Response 的必填项。下面是打开 Api Schema Snippit 的示例。

例如这里是 MerchantDetails 对象,其中我们有 'merchantName' 和 'merchantId' 作为必填字段。

MerchantDetails:
  description: Used to pass merchant specific data during the transaction.
  properties:
    merchantName:
      type: string
      maxLength: 64
    merchantId:
      type: string
      maxLength: 16
  required:
    - merchantName
    - merchantId

在响应中,我们使用相同的对象,但我们只想根据需要保留一个字段 'merchantId'。有什么方法可以在不创建新对象的情况下实现这一点?

MerchantDetails:
  description: Used to pass merchant specific data during the transaction.
  properties:
    merchantName:
      type: string
      maxLength: 64
    merchantId:
      type: string
      maxLength: 16
  required:
    - merchantId

您可以使用 readOnlywriteOnly 关键字将特定属性标记为仅在响应中或仅在请求中。

如果 readOnlywriteOnly 属性 包含在 required 列表中,required 仅影响相关范围 – 仅响应或仅请求.也就是说,read-only 必需属性仅适用于响应,write-only 必需属性 – 仅适用于请求。

不确定是否所有工具都支持这些关键字。我测试过 Redoc 可以正确生成文档。

MerchantDetails:
  description: Used to pass merchant specific data during the transaction.
  properties:
    merchantName: 
      type: string
      maxLength: 64
      writeOnly: true  # only in request
    merchantId:
      type: string
      maxLength: 16
  required:
    - merchantName
    - merchantId

请阅读 https://swagger.io/docs/specification/data-models/data-types/

中的 Read-Only 和 Write-Only 属性 部分