简体   繁体   English

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

[英]How is it possible to avoid the duplication of 401 error response for each api path? ( OpenApi 3 )

I defined my authentication in security and components/securitySchemes .我在securitycomponents/securitySchemes中定义了我的身份验证。 In the Swagger documentation about response , they provide this example:有关 response 的 Swagger 文档中,他们提供了以下示例:

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

I have a lot more paths than two, and to access any of them, the client has to be authenticated.我有比两条多得多的路径,要访问其中任何一条,必须对客户端进行身份验证。 I would like to avoid the '401' definition for each path, and define it once globally, if it is possible somehow.我想避免为每个路径定义“401”,并在全局范围内定义一次,如果可能的话。

How is it possible to use this response for each path?如何为每条路径使用此响应?

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

You can't, if you want the response to show up on that particular endpoint.如果您希望响应显示在该特定端点上,则不能。

I avoid the repetition in favour of important errors by not adding them to each endpoint and instead putting the well understood standard responses - 401, 403, 429, 404, 503 - on either a status endpoint or on the root method.我通过不将重要错误添加到每个端点,而是将易于理解的标准响应(401、403、429、404、503)放在状态端点或根方法上来避免重复出现有利于重要错误的错误。 eg:例如:

  '/{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'

The boilerplate responses would then all refer to the standard responses.然后,样板响应将全部引用标准响应。

Real endpoints then typically have a well defined response specific to that opearation and the things that may go specifically wrong.然后,实际端点通常具有特定于该操作的明确定义的响应以及可能 go 特别错误的事情。

  '/{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'

One thing I ensure is for error responses, the possible error codes for that operation are included in the response, like so:我确保的一件事是错误响应,该操作的可能错误代码包含在响应中,如下所示:

    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: ''     

Use an extension to add them in automatically as part of your build script.使用扩展将它们作为构建脚本的一部分自动添加。

What you're looking to do is not part of the OpenAPI standard.您要做的不是 OpenAPI 标准的一部分。 Responses are not inherited from parent objects;响应不是从父对象继承的; they must be explicitly added to every endpoint.它们必须显式添加到每个端点。 You can include a $ref for each response, but with a well-defined spec with lots of endpoints, you'll end up with a lot of duplication, and it's likely an endpoint might miss a response or two over time as additions and modifications are made.您可以为每个响应包含一个$ref ,但是使用具有许多端点的定义明确的规范,您最终会得到很多重复,并且随着时间的推移,端点可能会错过一两个响应作为添加和修改被制作。 Plus, it's simply not a good authoring experience.另外,这根本不是一个好的创作体验。

To prevent this problem, add an extension to your responses, like this:为防止出现此问题,请在您的回复中添加扩展名,如下所示:

responses:
  x-default-responses: true
  '418':
    description: Additional responses go here

The above spec will be the one that you work from.上述规范将是您使用的规范。 When done, have a script scan your completed yaml file, and replace that line with your list of default responses.完成后,让脚本扫描您完成的 yaml 文件,并将该行替换为您的默认响应列表。 Use this modified spec as the next stage of your development process (whatever it is you're using your OpenAPI spec for, be it documentation, testing, or SDK generation).将此修改后的规范用作开发过程的下一阶段(无论您使用 OpenAPI 规范做什么,无论是文档、测试还是 SDK 生成)。

While you could have your script add the responses without the extension property (after all, it is just YAML you're writing), I recommend you don't do this.虽然您可以让脚本添加没有扩展属性的响应(毕竟,您正在编写的只是 YAML),但我建议您不要这样做。 The extension makes your intent clear, so other editors will understand additional responses are present.该扩展使您的意图清晰,因此其他编辑将了解存在的其他响应。 Additionally, it is likely that (either now or one day in the future) you will have endpoints that do not conform to your default responses, so you wouldn't want to accidentally add those.此外,很可能(现在或将来的某一天)您将拥有不符合默认响应的端点,因此您不希望意外添加这些端点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM