LoginSignup
6
1

More than 3 years have passed since last update.

open api 空オブジェクト許容とダイナミックキーの書き方

Posted at

概要

open api 3(swagger)でAPI定義を書くとき、こういう定義ってどう書くんだろうと迷ったところを備忘録的に記録しておきます!

空オブジェクト許容

userオブジェクトが返るAPIがあります。そのAPIはuserがいないときは空オブジェクトを返します。

# user がいるとき
user: {id: 1, name: 'taro'}
# user がいないとき
user: {}

このような空オブジェクト許容を定義したいときは下記のように定義することができます、たぶん。

swagger editorではエラーにならないので間違ってはいないと思いますが、
下記イシューを見る感じ、色々と議論されているようです。

      responses:
        '200':
          description: user response
          content:
            application/json:
              schema:
                type: object
                required:
                  - user
                properties:
                  user:
                    oneOf:
                      - $ref: '#/components/schemas/User'
                      - {}

ダイナミックキー

ダイナミックキーは動的にキーが変わるスキーマです。

下記はuser_idがキー、user_nameが値のスキーマです。

このようなスキーマではキーの名前が毎回変わります。

user_id_name:
{
  1: 'taro'
}

この場合は、下記のように定義できます。

jsonの仕様上、キーは必ずstring型になるのでadditionalPropertiesのtypeは値のtypeのみを指定しています。

参考: https://swagger.io/docs/specification/data-models/dictionaries/

    UserIdName:
      type: object
      properties:
        additionalProperties:
          type: string

6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1