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. 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.
'/{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: ''
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…