Is it possible to provide recursive mapping for objects using same json_mapping?
exapmle:
person_json_mapping = api.model('Person', {
'name': fields.String(),
'date_of_birth': fields.Date(),
'parents': fields.List(fields.Nested(##person_json_mapping##))
}
how to use person_json_mapping inside self?
There is a way of defining recursive mapping with
flask_restplus
, with limitation that you must make an assumption on maximum recursion level your situation requires. You wouldn't want to reach Adam and Eva, would you?Instead of using
api.model
directly, write a method that builds that model recursively, decrementing an iteration_number argument in each recursive call.then remember to make a function call, when decorating your method with a marshaller, like this:
Note the round brackets!
It is also worth to note that
'Person'+str(iteration_number)
is mandatory if you use swagger. Without adding an iteration_number you will end up with recursion limit overflow, resulting in internal server error. Outside of swagger, mapper will do fine without it though.After making an arbitrary assumption of maximum level of recursion, it may also be a good idea to automatically notify admin of a situation when recursion limit was exceeded. That might be a responsibility of a method that prepares data, not the marshaller itself.