TL;DR:$ref
OpenAPI 3.1 支持兄弟姐妹。在以前的 OpenAPI 版本中,旁边的任何关键字都会$ref
被忽略。
开放API 3.1
迁移到 OpenAPI 3.1 后,您的定义将按预期工作。这个新版本与 JSON Schema 2020-12 完全兼容,它允许schemas$ref
中的兄弟姐妹。
openapi: 3.1.0
...
components:
schemas:
Time:
type: string
description: Time in 24 hour format "hh:mm".
TimeInterval:
type: object
properties:
lowerBound:
# ------- This will work in OAS 3.1 ------- #
$ref: "#/components/schemas/Time"
description: Lower bound on the time interval.
default: "00:00"
upperBound:
# ------- This will work in OAS 3.1 ------- #
$ref: "#/components/schemas/Time"
description: Upper bound on the time interval.
default: "24:00"
在模式之外- 例如,在响应或参数中 - $refs 只允许同级summary
和description
关键字。这些 $ref 旁边的任何其他关键字都将被忽略。
# openapi: 3.1.0
# This is supported
parameters:
- $ref: '#/components/parameters/id'
description: Entity ID
# This is NOT supported
parameters:
- $ref: '#/components/parameters/id'
required: true
OpenAPI 2.0 和 3.0.x
在这些版本中,$ref
通过将自身及其所有同级元素替换为它所指向的定义来工作。这就是为什么
lowerBound:
$ref: "#/definitions/Time"
description: Lower bound on the time interval.
default: "00:00"
变成
lowerBound:
type: string
description: Time in 24 hour format "hh:mm".
一种可能的解决方法是 wrap $ref
into allOf
- 这可用于将属性“添加”到 a$ref
但不覆盖现有属性。
lowerBound:
allOf:
- $ref: "#/definitions/Time"
description: Lower bound on the time interval.
default: "00:00"
另一种方法是使用$ref
内联定义替换。
definitions:
TimeInterval:
type: object
properties:
lowerBound:
type: string # <------
description: Lower bound on the time interval, using 24 hour format "hh:mm".
default: "00:00"
upperBound:
type: string # <------
description: Upper bound on the time interval, using 24 hour format "hh:mm".
default: "24:00"