gpt4 book ai didi

swagger - 避免在 Swagger 2.0 中使用样板代码

转载 作者:行者123 更新时间:2023-12-01 12:27:39 24 4
gpt4 key购买 nike

我的 API 遵循传统的状态代码,我发现自己在我的 API 定义的响应部分重复相同的文本

404:
description: The resource doesn't exist
schema:
$ref: '#/definitions/Error'
default:
description: An unexpected error has occurred
schema:
$ref: '#/definitions/Error'

我也遇到过一个类似的问题,就是无法分解出枚举属性和参数。我的 Swagger 代码可以变得更枯燥吗?

最佳答案

是的,您的代码可能会变得更加枯燥:OpenAPI(fka.Swagger)规范提供了许多分解事物的方法,包括响应、参数和枚举。

可重复使用的回复

您几乎可以像定义示例中的 Error 一样定义可重用响应。

首先添加response,例如Standard404,定义在根级别的responses

responses:
Standard404:
description: The resource doesn't exist
schema:
$ref: '#/definitions/Error'

然后,将它与 $ref : '#/responses/Standard404' 一起用于任何操作的 responses 中的 404 状态代码

responses:
404:
$ref: '#/responses/Standard404'

可重复使用的参数

对于可复用的参数,也是一样的。

首先添加一个参数,例如ID,定义在根级别的parameters中:

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 .

关于swagger - 避免在 Swagger 2.0 中使用样板代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37774783/

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