セキュリティ系の勉強・その他開発メモとか雑談. Twitter, ブログカテゴリ一覧
本ブログはあくまでセキュリティに関する情報共有の一環として作成したものであり,公開されているシステム等に許可なく実行するなど、違法な行為を助長するものではありません.

【Swagger3.0】1つのステータスコードに対して複数のレスポンスを定義 (oneOf)

//

状況

Swaggerで、とあるapiのレスポンスにおいて、「同じステータスコードを返すんだけれど、bodyの内容が違う場合がある」時、SwaggeroneOfという書き方で対応できます。(swagger3.0以上だったはず)


openapi: 3.0.0
...
省略
...
paths:
  /hello:
    get:
      tags:
        - hellos
      description: ハローが帰ってくるapiです。
      responses:
        '200':
          description: 登録されている支払い方法が返される。
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/responses/HelloResponse1'
                  - $ref: "#/components/responses/HelloResponse2"
              examples:
                response1:
                  summary: HelloResponse1の通常レスポンスです
                  value:
                    success1:
                      message_title: Response1
                      message: ハロー1のレスポンスのexampleです
                response2:
                  summary: HelloResponseの特別なレスポンスです
                  value:
                    success1:
                      message_title: Response2
                      message: ハロー2のレスポンスのexampleです
components:
  responses:
    HelloResponse1:
      type: object
      properties:
        success1:
          type: object
          properties:
            msg_title:
              type: string
              example: HelloResponse1
            message:
              type: string
              example: ハロー1のレスポンスです。
    HelloResponse2:
      type: object
      properties:
        success1:
          type: object
          properties:
            msg_title:
              type: string
              example: HelloResponse2
            message:
              type: string
              example: ハロー2のレスポンスです。



画面ではこう表示されます。 f:id:thinline196:20190918181302p:plain


examplesを定義したことにより、別のレスポンスを表示できるようになっています。 f:id:thinline196:20190918181502p:plain

f:id:thinline196:20190918181515p:plain


Schemaを選択すれば、oneOfを使用して定義した部分を見ることができます。 f:id:thinline196:20190918181701p:plain


あとはいい感じで定義してあげてください。レアケースかもしれませんが、意外と役立つと思います。