OpenAPIのネストされたオブジェクトと配列スキーマ

OpenAPI 3.0で深くネストされたオブジェクトスキーマ、オブジェクトの配列、複雑なデータ構造を定義。allOf、oneOf、discriminatorパターンによるスキーマ合成を学びます。

Schema Patterns

詳細な説明

OpenAPIのネストされたスキーマ

現実のAPIがフラットなデータ構造を扱うことはめったにありません。注文にはラインアイテムが含まれ、ユーザーには住所があり、設定にはネストされた設定項目があります。OpenAPIは複雑なネストされたスキーマを定義するためのいくつかのメカニズムを提供します。

ネストされたオブジェクト

components:
  schemas:
    UserProfile:
      type: object
      properties:
        id:
          type: string
          format: uuid
        name:
          type: string
        address:
          type: object
          properties:
            street:
              type: string
            city:
              type: string
            country:
              type: string

allOfによるスキーマ合成

ベーススキーマを拡張:

BaseEntity:
  type: object
  properties:
    id:
      type: string
      format: uuid
    created_at:
      type: string
      format: date-time

User:
  allOf:
    - $ref: "#/components/schemas/BaseEntity"
    - type: object
      required: [email]
      properties:
        email:
          type: string
          format: email

oneOfとdiscriminatorによる多態性

Notification:
  oneOf:
    - $ref: "#/components/schemas/EmailNotification"
    - $ref: "#/components/schemas/SmsNotification"
  discriminator:
    propertyName: type

ベストプラクティス

  • よく使用されるサブオブジェクトを名前付きスキーマに抽出する
  • プロパティのコピペではなく allOf を使用して継承する
  • 型安全な多態性のために oneOfdiscriminator を使用する
  • 可読性のためにネストの深さを3-4レベルに制限する

ユースケース

複雑なネストされたスキーマはEC(アイテム付き注文)、ソーシャルプラットフォーム(コメントとリアクション付き投稿)、エンタープライズシステム(ネストされた設定付きコンフィグ)で一般的です。正確なスキーマ定義により、コードジェネレーターがTypeScript、Go、Pythonなどで強く型付けされたモデルを生成でき、手動でのモデル作成が不要になりバグが削減されます。

試してみる — OpenAPI Editor & Viewer

フルツールを開く