是的,你的代码可能变得更加干燥:OpenAPI(fka。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'
可重复使用的参数
对于可重复使用的参数rs,这是一回事。
首先在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'
完整的示例
下面是这3个用例完整的例子:
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'
更多关于这 你应该阅读这tutorial(披露:我写的),并OpenAPI Specification。
也可以分解枚举吗? – Edmondo1984
@ Edmondo1984如果“排除枚举”意味着“我可以定义一个可重用枚举”,答案是否定的。你所能做的就是用枚举定义一个可重用属性(如我的答案所示)。也许我应该把这个精确度添加到我的答案中。我对你评论的理解是否正确? –