jshbrntt
jshbrntt

Reputation: 5404

How to define nullable response attributes?

I'm using the Python library connexion in conjunction with my Swagger specification which features the x-nullable attribute in some of the definitions.

This x-nullable attribute is essentially a polyfill for the lack of support for nullable attributes in OAS 2.0. However, most frameworks support it with varying degrees.

connexion does appear to support this attribute in parameters but not responses.

So if you attempt to return a response with null as a value for any of items return in a response with x-nullable and validate_responses set to True it will fail validation and produce Response body does not conform to specification in the response.

How best can I polyfill support for x-nullable in a connexion based Python application such as the ones generate from the swagger-codegen tool?

Upvotes: 1

Views: 928

Answers (1)

jshbrntt
jshbrntt

Reputation: 5404

Managed to specify a custom validator that patches the JSON schema's in the definition of the operation passed to it.

from connexion.decorators.response import ResponseValidator

class CustomResponseValidator(ResponseValidator):
    def __init__(self, operation,  mimetype):
        operation.definitions = { name: self.patch_nullable_in_definition(definition) for name, definition in operation.definitions.items() }
        ResponseValidator.__init__(self, operation, mimetype)

    def patch_nullable_in_definition(self, definition):
        definition['properties'] = { key: property_ if '$ref' in property_ else self.patch_nullable_in_property(property_) for key, property_ in definition['properties'].items() }
        return definition

    def patch_nullable_in_property(self, property_):
        if isinstance(property_, dict) and \
           not isinstance(property_, list) and \
           'x-nullable' in property_ and \
           property_['x-nullable'] and \
           'type' in property_:
            if not isinstance(property_['type'], list):
                property_['type'] = [property_['type']]
            if not 'null' in property_['type']:
                property_['type'].append('null')
        return property_

Upvotes: 1

Related Questions