How do you serialize of "connexion model" (object) created by swagger.io? There is no example of how to serialize an object to a HTTP response. There seems to be no functions in the object for this as well, even though the documentation states "Otherwise, and by default and if the specification defines that an endpoint produces only JSON, connexion will automatically serialize the return value for you and set the right content type in the HTTP header"
expect the following would return HTTP Response with JSON serialization of FooDef
def aaa_post(name=None):
a = FooDef(abc="yes")
return a
TypeError: Object of type 'FooDef' is not JSON serializable
Create a model in swagger.io and use codegen to make models and ... Then try to use model to serialize to Response.
Output of the commands:
Python 3.6.1 :: Continuum Analytics, Inc.
connexion 1.1.10
Python objects are not inherently JSON serialize by default. If you return something that fits in JSON (list, dict, etc) it will just work and automatically serialize it for you. If you are acting on python objects, the easiest thing would probably be to add a serialize method yourself to turn them into dictionaries, lists, or what have you. I use something like this in my projects:
class IpAddress(db.Model):
__tablename__ = "ip_address"
id = db.Column(db.Integer, primary_key=True)
ip_address = db.Column(db.String(200), nullable=False, unique=True)
def serialize(self):
return {
'id': self.id,
'ip_address': self.ip_address
}
def get_ip_address(ip_address_id):
ip = IpAddress.query.filter_by(id=ip_address_id).one()
return ip.serialize()
Thanks, I figured that was the case. Two suggestions:
1) put an example of this in your documentation about Response Handling or note objects have to serialize themselves to json or xml string.
2) If your project supports the swagger.io codegen that generates Python code based on connexion, then add code to generate a serialize function.
Well, after some digging, turns out swagger.io codegen created a to_dict() function in the base class that can be used, json.dumps(xx.to_dict()).
Sweet :)
This probably isn't news to you, but just in case you or someone looking at this later doesn't know, if you are in a connexion endpoint you shouldn't even need to json.dumps() it. You could just return it directly (return xx.tod_dict()), and connexion will take care of dumping it and setting the JSON headers for you. Or if it was a normal flask endpoint, you could do return jsonify(xx.to_dict()) to make sure the headers properly get set.
Cheers!
thanks, that is helpful. Would be nice if you had that in documentation. Also I would have never used connexion if it was not used by swagger.io, so you might want to think about documentation for code generated there.
@rmundkowsky thanks, I never looked into swagger.io code generation..