はじめに
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}))