是的,您的代码可以变得更加干净:OpenAPI(之前称为Swagger)规范提供了许多方法来分解事物,包括响应、参数和枚举。
可重用的响应
您几乎可以以与示例中定义
Error
相同的方式定义可重用的响应。
首先,在根级别的
responses
中添加响应,例如
Standard404
。
responses:
Standard404:
description: The resource doesn't exist
schema:
$ref: '#/definitions/Error'
然后,在任何操作的responses
中使用$ref : '#/responses/Standard404'
来处理404状态码。
responses:
404:
$ref: '#/responses/Standard404'
可重复使用的参数
对于可重复使用的参数,处理方式相同。
首先,在根级别的parameters
中添加一个参数,例如ID
:
parameters:
ID:
name: id
in: path
required: true
type: string
然后在任何参数列表中使用它,格式为$ref: '#/parameters/ID'
。
提示: 参数可以在操作级别和路径级别上定义:
/other-resources/{id}:
get:
parameters:
- $ref: '#/parameters/ID'
/resources/{id}:
parameters:
- $ref: '#/parameters/ID'
可重用的枚举
您只需要使用枚举定义一个字符串类型(或整数类型或数字类型)即可:
SomeValueWithEnum:
type: string
enum:
- a value
- another value
然后您可以像这样随意使用它:
Resource:
properties:
dummyProperty:
$ref: '#/definitions/SomeValueWithEnum'
完整示例
以下是这三种用例的完整示例:
swagger: '2.0'
info:
version: 1.0.0
title: API
description: Reusable things example
paths:
/resources:
post:
responses:
200:
description: OK
default:
$ref: '#/responses/Default'
/resources/{id}:
parameters:
- $ref: '#/parameters/ID'
get:
responses:
200:
description: OK
404:
$ref: '#/responses/Standard404'
default:
$ref: '#/responses/Default'
delete:
responses:
200:
description: OK
404:
$ref: '#/responses/Standard404'
default:
$ref: '#/responses/Default'
/other-resources/{id}:
get:
parameters:
- $ref: '#/parameters/ID'
responses:
200:
description: OK
404:
$ref: '#/responses/Standard404'
default:
$ref: '#/responses/Default'
definitions:
Error:
properties:
message:
type: string
SomeValueWithEnum:
type: string
enum:
- a value
- another value
Resource:
properties:
dummyProperty:
$ref: '#/definitions/SomeValueWithEnum'
AnotherResource:
properties:
anotherDummyProperty:
$ref: '#/definitions/SomeValueWithEnum'
parameters:
ID:
name: id
in: path
required: true
type: string
responses:
Standard404:
description: The resource doesn't exist
schema:
$ref: '#/definitions/Error'
Default:
description: An unexpected error has occurred
schema:
$ref: '#/definitions/Error'
关于此事的更多信息
你应该阅读这篇教程(声明:本人撰写),以及OpenAPI规范。
$ref: '#/components/responses/common_errors'
混合使用,但是我收到了警告sibling values alongside $refs are ignored
和错误... should only have three-digit status codes
。有没有办法简化在不同端点重复的几个响应代码? - David Hempy