LoginSignup
0
1

More than 5 years have passed since last update.

pythonのjsonschemaライブラリでswagger用にx-nullableに対応する方法

Last updated at Posted at 2017-04-14

はじめに

swaggerはjsonschemaと完全に互換性があるわけではない。pythonでjsonschemaでのvalidationにはjsonschemaというそのままな名前のライブラリを使うのだけれど。

以前記事を書いた通りに、swaggerはnull typeを許容していない。とは言え、nullを返したい場合もあったりするのでそれに対応する方法のメモ。

x-nullableのサポート

幾つかのswagger用のツールではnullableのサポートに x-nullable という属性を追加している。swagger的には x- で始まる属性は自由に付けることが許されている。

これに対応する方法は以下の様な感じ。

from jsonschema.validators import Draft4Validator, extend
from jsonschema._validators import type_draft4


def type_custom(validator, types, instance, schema, nullable_attr="x-nullable"):
    if schema.get(nullable_attr, False):
        if not isinstance(types, (list, tuple)):
            types = [types]
        types.append("null")
    yield from type_draft4(validator, types, instance, schema)


CustomValidator = extend(Draft4Validator, {
    "type": type_custom,
})

実際こんな感じで使える。


schema = {
    "type": ["string", "null"]
}

validate = CustomValidator(schema).validate
print(validate(None, schema))
print(validate(None, {"type": "string", "x-nullable": True}))
0
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
0
1