我们支持 API 指南目录,我们在其中记录并显示系统中存在的不同 Web 服务。有许多容器将相关服务分组,但很少有服务具有通用架构/模型。 例如,忽略标识符,因为这是一个示例 创建一个人 - POST - [姓名、电子邮件、年龄] 获取所有人 - GET - [姓名、电子邮件、年龄] 列表
上面的2个调用具有相同的模型,
"name" : {
"type" : "string",
"description" : "name of the persion"
},
"email" : {
"type" : "string",
"description" : "user email id",
"example" : "[email protected]"
},
"age" : {
"type" : "integer",
"description" : "user age",
"example" : 20
}
到目前为止,我们一直对 GET/POST 调用使用相同的模式,现在我们想要添加字段上可能存在的其他验证,例如,名称不能包含数字..
"name" : {
"type" : "string",
"description" : "name of the persion",
**"validation" : "name cannot contain numbers"**
},
"email" : {
"type" : "string",
"description" : "user email id",
"example" : "[email protected]"
},
"age" : {
"type" : "integer",
"description" : "user age",
"example" : 20
}
如您所见,此验证仅对 POST 请求有意义,对 get 请求无效,
那么,在这种情况下,什么是好的设计呢?
有任何行业标准记录吗?有什么经验/例子吗?只是想了解一些想法!
开展讨论,学习和讨论对于许多人可能面临或将要面临的问题,更好的设计是什么。
我将保留具有公共元素的模式,然后创建定义附加元素的其他模式。
所以如果你的通用模型定义如下
components:
schemas:
common:
type: object
properties:
foo:
type: string
您可以创建一个辅助架构来引用该架构并添加其他元素,甚至添加到预先存在的属性中。
components:
schemas:
common:
type: object
properties:
foo:
type: string
common-with-validation:
allOf:
- $ref: #/components/schemas/common
- properties:
foo:
maxLength: 50
在本文档中,
common-with-validation
模式以 common
模式开始,并向 maxLength
属性的现有要求添加 foo
。我不需要重新指定有效负载是一个对象或者 foo
是一个字符串,因为引用已经做了这些事情。