Search code examples
pythonjsonnestedswaggerflask-restplus

Flask-restful using nested fields to generate docs with nested response, getting TypeError: Object of type Nested is not JSON serializable


I am using flask-restx / flask-restplus, trying utilize the swagger documentation generation feature. I have this setup for my models.

A = api.model(
    'A', {
        "a1": fields.String(description=''),
        "a2": fields.String(description='')
    }
)

B = api.model(
    'B', {
        "b1": fields.String(description=''),
        "b2": fields.String(description='')
    },
)

response_with_nested_data = api.model(
    "TLD", {
        "A": fields.Nested(
            A, description=''
            ),
        "B": fields.Nested(
            B, description=''
        )
    }
)

And I have a handler that looks like

@myapi.route('/aa', methods=['POST'])
class AA(Resource):
    @myapi.expect(simple_expected_model)
    @myapi.response(200, response_with_nested_data)
    @do_auth(require_token=True, render_errors=True)
    def post(self):
        return handle_request(request)

I am trying to get output from this api endpoint, in the swagger docs, that looks like

{
    "A": {
        "a1": "a",
        "a2": "aa"
    }
    "B": {
        "b1": "b",
        "b2": "bb"
    }
}

but when spin up my server and hit my swagger docs generation page I get an error

TypeError: Object of type Nested is not JSON serializable

So I know I am doing something wrong here. Any ideas where I am going wrong and what I should be doing instead?


Solution

  • I ended up fixing the issue by using keywords in the decorator.

     @myapi.response(200, response_with_nested_data)
    

    became

    @myapi.response(code=200, model=response_with_nested_data, description='')