我正在为具有特定负载结构的 API 端点创建 Swagger/OpenAPI 规范:
这是我尝试过的:
openapi: 3.0.0
info:
title: My API
version: 1.0.0
paths:
/my-endpoint:
post:
requestBody:
required: true
content:
application/json:
schema:
type: object
required:
- mandatoryField
properties:
mandatoryField:
type: string
optionalFieldOne:
type: string
optionalFieldTwo:
type: string
I am stuck here.
最简单的方法是使用
maxProperties: 2
并通过 additionalProperties: false
禁止额外的属性。这确保最多只能提供一个可选属性。
type: object
required:
- mandatoryField
properties:
mandatoryField:
type: string
optionalFieldOne:
type: string
optionalFieldTwo:
type: string
maxProperties: 2
additionalProperties: false
定义互斥属性的另一种方法是使用
not
+ required
禁止同时存在这些属性(但在我看来,具有 not
的模式可读性较差)。
type: object
required:
- mandatoryField
properties:
mandatoryField:
type: string
optionalFieldOne:
type: string
optionalFieldTwo:
type: string
# This means: if both optionalFieldOne and optionalFieldTwo are present
# then the schema is not valid
not:
required:
- optionalFieldOne
- optionalFieldTwo