gpt4 book ai didi

swagger - 如何避免每个 api 路径重复 401 错误响应? (开放式 API 3)

转载 作者:行者123 更新时间:2023-12-05 06:52:52 32 4
gpt4 key购买 nike

我在 securitycomponents/securitySchemes 中定义了我的身份验证。在Swagger documentation about response ,他们提供了这个例子:

paths:
/something:
get:
...
responses:
...
'401':
$ref: '#/components/responses/UnauthorizedError'
post:
...
responses:
...
'401':
$ref: '#/components/responses/UnauthorizedError'
...
components:
responses:
UnauthorizedError:
description: Authentication information is missing or invalid
headers:
WWW_Authenticate:
schema:
type: string

我的路径比两条多得多,要访问其中任何一条,客户端都必须经过身份验证。我想避免为每个路径定义“401”,并在可能的情况下全局定义一次。

如何为每个路径使用此响应?

'401':
$ref: '#/components/responses/UnauthorizedError'

最佳答案

如果您希望响应显示在该特定端点上,则不能。

我避免重复支持重要错误,方法是不将它们添加到每个端点,而是将众所周知的标准响应 - 401、403、429、404、503 - 放在状态端点或根方法上。例如:

  '/{foo}/{bar}/status':
get:
tags:
- api
responses:
'200':
description: successful response with a resource
content:
application/json:
schema:
$ref: '#/components/schemas/statusResponse'
'400':
$ref: '#/components/responses/400_error_response'
'401':
$ref: '#/components/responses/401_error_response'
'403':
$ref: '#/components/responses/403_error_response'
'404':
$ref: '#/components/responses/404_error_response'
'500':
$ref: '#/components/responses/500_error_response'

样板响应将全部引用标准响应。

然后,真实的端点通常会针对该操作以及可能出现的具体错误的事情定义明确的响应。

  '/{foo}/{bar}/segment':
post:
summary: checks username is found or not
description: |-
checks username and returns 204 if found else 403
operationId: checkUsername
tags:
- Login
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/segment_POST_request'
responses:
'200':
$ref: '#/components/responses/segment_POST_200_response'
'403':
$ref: '#/components/responses/403_forbidden_response'
'500':
$ref:
'#/components/responses/500_internal_server_error_replayable_response'

我确保的一件事是错误响应,该操作的可能错误代码包含在响应中,如下所示:

    500_internal_server_error_replayable_response:
description: |-
The following `500 Internal Server Error` errors can occur during the API processing.

| errorCode | cause | details |
| - | - | - |
| `SOME.ERROR.500` | There was an error processing the request either in Foo or on a downstream system | A request to something failed, Bar or Baz however the error is recoverable and can be replayed |
| `SOME.ERROR.014` | Baz returned a `404` during the migration operation, even though it has previously confirmed the member exists | This is a fatal error during the migration process and cannot be recovered. The request should not be replayed. |
headers:
content:
application/json:
schema:
$ref: '#/components/schemas/errorResponse'
example:
status: '500'
errorCode: SOME.ERROR.500
errorDescription: The request could not be processed
errorSubCode: ''
furtherDetails: ''
docLink: ''

关于swagger - 如何避免每个 api 路径重复 401 错误响应? (开放式 API 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65890740/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com