如何在 OpenAPI (Swagger) 中将 $ref 属性声明为只读?

问题描述 投票:0回答:4

在此示例中,我尝试为“House”添加只读字段。房子是另一个我想要只读的模型。

在此示例中,可以将 Dogs 数组设置为

readOnly
而不会出现错误,但是当我将 House 的单个定义设置为
readOnly
时,我在 Swagger 编辑器中收到以下警告:

同级值不允许与 $refs 一起使用

我理解这是因为模型中的所有内容都是继承在这里的。那么,如何定义写入 API 调用不能在此端点中定义“House”,同时又允许在另一个 API 端点中创建和更新 House?

Pets:
  properties:
    id:
      type: string
      example: AAAAE12-1123AEF-1122312123
      readOnly: true
    name:
      type: string
      example: My Default Name
    text:
      type: string
      example: My Default Text
  Dogs:
    type: array
    readOnly: true
    items:
      $ref: '#/definitions/Dog'    
  House:
    readOnly: true
    $ref: '#/definitions/House'
swagger swagger-2.0 openapi
4个回答
56
投票

开放API 3.1

在 OAS 3.1 中,模式定义支持同级关键字

$ref
:

House:
  $ref: '#/components/schemas/House'
  readOnly: true

OpenAPI 3.0 和 2.0

$ref
旁边的同级关键字将被忽略。解决方法是使用
allOf
$ref
与其他属性组合:

  House:
    readOnly: true
    allOf:
      - $ref: '#/definitions/House'

2
投票

我刚刚找到结果并想与您分享,如下所示,您可以使用readyonly属性来隐藏任何字段:

  • Java代码:

@ApiModelProperty(example = "1", readOnly = true, value = "User status")

public String getUserStatus() { return userStatus; }

  • 大摇大摆: enter image description here

1
投票

跟进Helen的回答

OpenAPI 3.0.x

allOf 引用模式定义旁边带有 readonly 的解决方案不适用于 oas3-chow-chow 等库,不确定它是否适用于其他库。我能够通过将只读定义转移到 allOf 块中来使其工作,如下所示:

  House:
    allOf:
      - $ref: '#/definitions/House'
      - readOnly: true

0
投票

在 OpenAPI 3.0.3 中,它对我有用。

House:
  readOnly: true
  allOf: 
    - $ref: '#/components/schemas/House'
© www.soinside.com 2019 - 2024. All rights reserved.