swagger is not fully compatible with json schema. I use a library with the same name as jsonschema for validation with jsonschema in python.
As I wrote earlier, swagger does not allow null types. However, there are times when you want to return null, so a note on how to deal with it.
Some tools for swagger add the attribute x-nullable
to the support for nullable. In terms of swagger, attributes starting with x-
are allowed to be attached freely.
The method to deal with this is as follows.
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,
})
You can actually use it like this.
schema = {
"type": ["string", "null"]
}
validate = CustomValidator(schema).validate
print(validate(None, schema))
print(validate(None, {"type": "string", "x-nullable": True}))
Recommended Posts