问题描述
我正在为现有API编写OpenAPI规范.该API会针对成功和失败返回状态200,但具有不同的响应结构.
I'm writing an OpenAPI spec for an existing API. This API returns status 200 for both success and failure, but with a different response structure.
例如,在注册API中,如果用户成功注册,则该API使用以下JSON发送状态200:
For example, in the signup API, if the user signed up successfully, the API sends status 200 with the following JSON:
{
"result": true,
"token": RANDOM_STRING
}
如果有重复的用户,API也会发送状态200,但带有以下JSON:
And if there is a duplicated user, the API also sends status 200, but with the following JSON:
{
"result": false,
"errorCode": "00002", // this code is duplicated error
"errorMsg": "duplicated account already exist"
}
在这种情况下,如何定义响应?
In this case, how to define the response?
推荐答案
在OpenAPI 3.0中可行,但在2.0中则不可行.
This is possible in OpenAPI 3.0 but not in 2.0.
OpenAPI 3.0支持oneOf
,用于指定响应的备用模式.您还可以添加多个响应examples
,例如成功和失败的响应.从3.23.0版开始,Swagger UI支持多个examples
.
OpenAPI 3.0 supports oneOf
for specifying alternate schemas for the response. You can also add multiple response examples
, such as successful and failed responses. Swagger UI supports multiple examples
since v. 3.23.0.
openapi: 3.0.0
...
paths:
/something:
get:
responses:
'200':
description: Result
content:
application/json:
schema:
oneOf:
- $ref: '#/components/schemas/ApiResultOk'
- $ref: '#/components/schemas/ApiResultError'
examples:
success:
summary: Example of a successful response
value:
result: true
token: abcde12345
error:
summary: Example of an error response
value:
result: false
errorCode: "00002"
errorMsg: "duplicated account already exist"
components:
schemas:
ApiResultOk:
type: object
properties:
result:
type: boolean
enum: [true]
token:
type: string
required:
- result
- token
ApiResultError:
type: object
properties:
result:
type: boolean
enum: [false]
errorCode:
type: string
example: "00002"
errorMsg:
type: string
example: "duplicated account already exist"
在OpenAPI/Swagger 2.0中,每个响应代码只能使用一个架构,因此,您最多只能将各种字段定义为可选字段,并在模型description
或操作description
中记录其用法. /p>
In OpenAPI/Swagger 2.0, you can only use a single schema per response code, so the most you can do is define the varying fields as optional and document their usage in the model description
or operation description
.
swagger: "2.0"
...
definitions:
ApiResult:
type: object
properties:
result:
type: boolean
token:
type: string
errorCode:
type: string
errorMsg:
type: string
required:
- result
这篇关于如何在OpenAPI(Swagger)中为相同的HTTP状态代码定义不同的响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!