$ref を使用すると Swagger スキーマ プロパティが無視されるのはなぜですか? 質問する

$ref を使用すると Swagger スキーマ プロパティが無視されるのはなぜですか? 質問する

私は、単純な文字列を使用して時間を格納する、時間間隔の Swagger モデルを構築しようとしています (datetime もあることは知っています)。

definitions:
  Time:
    type: string
    description: Time in 24 hour format "hh:mm".
  TimeInterval:
    type: object
    properties:
      lowerBound:
        $ref: "#/definitions/Time"
        description: Lower bound on the time interval.
        default: "00:00"
      upperBound:
        $ref: "#/definitions/Time"
        description: Upper bound on the time interval.
        default: "24:00"        

何らかの理由で、生成された HTML には lowerBound と upperBound の「説明」が表示されず、元の Time の「説明」のみが表示されます。このため、正しく実行できていないのではないかと思います。

したがって、問題は、モデルを型として使用することが、私がやろうとしているように実際に実行できるかどうかです。

ベストアンサー1

TL;DR:$ref兄弟は OpenAPI 3.1 で (ある程度) サポートされています。以前の OpenAPI バージョンでは、横にあるキーワードはすべて$ref無視されます。

オープンAPI3.1

OpenAPI 3.1に移行すると、定義は期待どおりに機能します。この新しいバージョンはJSON Schema 2020-12と完全に互換性があり、$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 では兄弟summarydescriptionキーワードのみが許可されます。これらの $refs の横にあるその他のキーワードは無視されます。

# 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

追跡/賛成できる非スキーマ $ref 兄弟に関する OpenAPI 機能リクエストをいくつか示します。

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 $refinto を使用することですallOf。これを使用すると、属性を「追加」できます$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"

おすすめ記事