问题描述
我正在为现有 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
,例如成功和失败的响应.Swagger UI 自 v. 3.23.0 起支持多个 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
或操作中记录它们的用法描述
.
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 状态代码定义不同的响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!