tech

テックカテゴリー

【OpenAPI】1つのステータスコードに対して複数のレスポンスを定義する

Category | server

Tag | OpenAPI / Tips

Author | naohito-T

Post | 2023-02-13 / 34,254views

【OpenAPI】oneOfを使用した実装

概要


1つのステータスコードに対しbody レスポンスが複数ある事象に遭遇しました。
結論としてAPI認可などにより返すbody レスポンスの内容が違う場合がある時、oneOf という書き方で対応ができることができます。

複数レスポンス 例


以下で例文を記載しますが、お急ぎの方はコピペしちゃってください。

openapi: 3.0.0
---
省略
---
paths:
  /sample:
    get:
      tags:
        - samples
      description: sample api sampleが返ってきます
      responses:
        "200":
          description: sample api 成功レスポンス
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/responses/SampleResponse1"
                  - $ref: "#/components/responses/SampleResponse2"
              examples:
                response1:
                  summary: sample api 成功レスポンスの通常レスポンス
                  value:
                    success1:
                      message_title: Response1
                      message: sample
                response2:
                  summary: sample api 成功レスポンスの認可により絞られた特殊レスポンス
                  value:
                    success1:
                      message_title: Response2
                      message: special sample
components:
  responses:
    SampleResponse1:
      type: object
      properties:
        success1:
          type: object
          properties:
            msg_title:
              type: string
              example: SampleResponse1
            message:
              type: string
              example: sample
    SampleResponse2:
      type: object
      properties:
        success1:
          type: object
          properties:
            msg_title:
              type: string
              example: SampleResponse2
            message:
              type: string
              example: special sample


プレビュー確認


例の内容を記載するとOpenAPIがよしなにレスポンスを記載してくれます。
examples を定義したことにより、別のレスポンスを表示できるようになっています。

Schemaを選択すれば、oneOfを使用して定義した部分を見ることができます。


以上です。

Share this article

naohito-T

naohito-T

千葉出身。都内(銀座)での美容師経験があるソフトウェアエンジニア。モデル撮影のために購入したmacを使っていたらPCの仕組みが気になり始め、気づいたらエンジニアに。人生まるごとクリエイティブだと思っている。人の髪をデザインしていた経験をIT業界へ活かせることはないか日々模索中。