在此示例中,我尝试为“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'
在 OAS 3.1 中,模式定义支持同级关键字
$ref
:
House:
$ref: '#/components/schemas/House'
readOnly: true
$ref
旁边的同级关键字将被忽略。解决方法是使用 allOf
将 $ref
与其他属性组合:
House:
readOnly: true
allOf:
- $ref: '#/definitions/House'
跟进Helen的回答
allOf 引用模式定义旁边带有 readonly 的解决方案不适用于 oas3-chow-chow 等库,不确定它是否适用于其他库。我能够通过将只读定义转移到 allOf 块中来使其工作,如下所示:
House:
allOf:
- $ref: '#/definitions/House'
- readOnly: true
在 OpenAPI 3.0.3 中,它对我有用。
House:
readOnly: true
allOf:
- $ref: '#/components/schemas/House'