我在OpenAPI 3.0中有一个数据模型定义,使用SwaggerHub显示UI。我希望模型的属性之一为related
,它是同一模型的属性数组。
Foo:
properties:
title:
type: string
related:
type: array
items:
$ref: '#/components/schemas/Foo'
解析器似乎不喜欢这样-UI将related
属性显示为空数组。这种自引用在OpenAPI 3.0中是否可能?
答案 0 :(得分:1)
您的定义是正确的,只是Swagger UI当前无法正确呈现循环引用的定义。有关详细信息,请参见issue #3325。
您可以做的是添加一个模型example
,Swagger UI将显示此示例,而不是尝试从定义中生成示例。
Foo:
type: object
properties:
title:
type: string
related:
type: array
items:
$ref: '#/components/schemas/Foo'
example: # <-------
title: foo
related:
- title: bar
- title: baz
related:
- title: qux
或者,您可以仅为example
数组添加一个related
:
Foo:
type: object
properties:
title:
type: string
related:
type: array
items:
$ref: '#/components/schemas/Foo'
example: # <--- Make sure "example" is on the same level as "type: array"
- title: bar
- title: baz
related:
- title: qux
答案 1 :(得分:0)
我已经厌倦了这种讨厌的情况,所以我完全没有任何示例,而是选择摆脱了items属性,添加了description元素并使用了一个空数组:
Foo:
type: object
properties:
title:
type: string
related:
type: array
description: Array of Foo elements
example: []
答案 2 :(得分:0)
您可以通过代理模型来实现:
...
_MessageProxy:
description: Message
type: object
required:
- id
- user
- body
- publishedAt
properties:
id:
title: Message id
type: string
readOnly: true
example: '595f4acf828b0b766ad11290'
user:
$ref: '#/components/schemas/User'
Message:
allOf:
- $ref: '#/components/schemas/_MessageProxy'
- type: object
properties:
parent:
title: Parent
readOnly: true
allOf:
- $ref: '#/components/schemas/_MessageProxy'
...
答案 3 :(得分:0)
使用虚拟模型和交叉引用:
Foo:
properties:
title:
type: string
related:
type: array
items:
$ref: '#/components/schemas/_Foo'
_Foo:
properties:
title:
type: string
related:
type: array
items:
$ref: '#/components/schemas/Foo'