我有一个API,要么成功返回以下响应:
{
"result": "success",
"filename": "my-filename.txt"
}
Run Code Online (Sandbox Code Playgroud)
失败后如下:
{
"result": "error",
"message": "You must specify the xxx parameter."
}
Run Code Online (Sandbox Code Playgroud)
仅当请求成功时才指定filename属性,但如果出现错误则提供消息.这意味着消息和文件名属性是"可选的",但结果属性是必需的.
我尝试在定义中定义此响应对象,如下所示:
"my_response_object": {
"type": "object",
"properties": {
"result": {
"type": "string",
"description": "value of 'success' or 'error', indicated whether was successful",
"required": true
},
"message": {
"type": "string",
"description": "an error message if there was an issue",
"required": false
},
"filename": {
"type": "string",
"description": "the filename to return if the request was successful",
"required": false
}
}
}
Run Code Online (Sandbox Code Playgroud)
但似乎swagger不喜欢"required"属性,并将显示以下错误消息:

当我从swagger看一个例子时,他们有以下布局,其中有两个不同的响应定义而不是一个.
"responses": {
"200": {
"description": "Profile information for a user",
"schema": {
"$ref": "#/definitions/Profile"
}
},
"default": {
"description": "Unexpected error",
"schema": {
"$ref": "#/definitions/Error"
}
}
}
Run Code Online (Sandbox Code Playgroud)
我可以做到这一点,但似乎不能有200个错误代码的多个响应.这是否意味着必须对所有错误响应使用"default",并且对于所有错误响应只能使用单个结构,或者是否有方法指定某些属性在定义中是可选的?
Ron*_*Ron 46
您在模型中收到错误,因为这不是定义所需属性的方法.
正确的形式是:
"my_response_object": {
"type": "object",
"required": [ "result" ],
"properties": {
"result": {
"type": "string",
"description": "value of 'success' or 'error', indicated whether was successful"
},
"message": {
"type": "string",
"description": "an error message if there was an issue"
},
"filename": {
"type": "string",
"description": "the filename to return if the request was successful"
}
}
}
Run Code Online (Sandbox Code Playgroud)
任何不属于该required属性的东西都被认为是可选的.请记住,这意味着它可能得到两个 message和filename.
然后,您可以使用此模型进行200响应.
但是 - 在REST API设计方面,这打破了一个更常见的标准.从HTTP协议获取的状态代码旨在传达操作的结果.2XX用于成功响应,4XX用于因用户输入错误而导致的错误,5XX用于服务器端的问题(3XX用于重定向).你在这里做的是告诉客户 - 操作是成功的,但事实上,这可能是一个错误.
如果您仍然可以修改API,我强烈建议使用状态代码进行区分,即使使用精细调整的区别,例如200用于成功的GET操作,201用于成功的POST(或创建)操作等等,基于关于这里的定义 - http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
| 归档时间: |
|
| 查看次数: |
37493 次 |
| 最近记录: |