Swagger 如果模式有其他引用,如何在OpenAPI3中为GET和POST请求引用相同的模式
我有以下OpenAPI 3模式:Swagger 如果模式有其他引用,如何在OpenAPI3中为GET和POST请求引用相同的模式,swagger,openapi,Swagger,Openapi,我有以下OpenAPI 3模式: { ..., "components": { "schemas": { "User": { "type": "object", "properties": { "id": { "type": "
{
...,
"components": {
"schemas": {
"User": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64",
"readOnly": true
},
"name": {
"type": "string"
}
}
},
"Report": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64",
"readOnly": true
},
"user": {
"$ref": "#/components/schemas/User"
}
}
}
}
}
}
现在,如果我同时为User和Report指定GET请求,一切看起来都很好。用户的POST请求也在工作。但是,后报告请求不起作用。报告发布请求的主体应如下所示:
{
"user": {
"id": 1
}
}
"user": {
"id": {
"type": "integer",
"format": "int64",
"readOnly": true
}
}
"schemas": {
"userId": {
"type": "integer",
"format": "int64",
"readOnly": true
},
"userName": {
"type": "string"
},
"User": {
"type": "object",
"properties": {
"id": {
"$ref": "#/components/schemas/userId"
},
"name": {
"$ref": "#/components/schemas/userName"
}
}
}
因此,不应指定“name”属性,因为它只是对已经存在的用户的引用,并且将根据id进行匹配
是否可以编写报告POST请求,以便它理解只应指定用户的id?或者我必须创建两个不同的报告模式,一个用于GET请求,另一个用于POST请求?有几种方法可以解决这个问题。您可以专门为POST创建定义,也可以将
User
定义拆分为更多原子组件以供重用
备选案文1:多重定义
将您的报告user
定义构造为如下内容:
{
"user": {
"id": 1
}
}
"user": {
"id": {
"type": "integer",
"format": "int64",
"readOnly": true
}
}
"schemas": {
"userId": {
"type": "integer",
"format": "int64",
"readOnly": true
},
"userName": {
"type": "string"
},
"User": {
"type": "object",
"properties": {
"id": {
"$ref": "#/components/schemas/userId"
},
"name": {
"$ref": "#/components/schemas/userName"
}
}
}
这样做的好处是快速简单,不会影响你的其他定义。但这会导致大量代码重复,未来对设计的任何更改都需要确保不会遗漏这些特殊定义
选项2:拆分并重用定义
您有两个不同的属性,它们有不同的用途,在多个定义中使用。这是一个很好的参考。将用户定义拆分为多个模式。大概是这样的:
{
"user": {
"id": 1
}
}
"user": {
"id": {
"type": "integer",
"format": "int64",
"readOnly": true
}
}
"schemas": {
"userId": {
"type": "integer",
"format": "int64",
"readOnly": true
},
"userName": {
"type": "string"
},
"User": {
"type": "object",
"properties": {
"id": {
"$ref": "#/components/schemas/userId"
},
"name": {
"$ref": "#/components/schemas/userName"
}
}
}
这允许您使用与id
实际定义相同的id
重用报告中的userId
。当您开始将定义扩展到一个更大的API时,这种方法可能开始变得难以理解,但随着API形状的改变,这种方法的可维护性会大大提高。请注意,这也有助于定义用户ID和报告ID之间的差异,虽然共享相同的名称,但可能包含不同的数据,并且随着时间的推移,可能有不同的规则