Search code examples
pythonflaskmongoengineflask-restfulmarshmallow

When would I use an external serializer like marshmallow over monogoengine's in-built JSON serialization (from_json and to_json)?


I am writing a simple REST API in Python using Flask-RESTful and their documentation says that they are planning to deprecate their object serialization (reqparse) in favor of serializers like marshmallow My API is reading and writing from a MongoDB doc store, using Flask MongoEngine.

I would very much appreciate an example of a use case where I would choose to use an external serializer such as Marshmallow over the MongoEngine built-in serializers on Document object.


Solution

  • Mongo uses BSON and they have a dedicated parser util implemented in python.
    From source:

    Deserialization:

    from bson.json_util import loads
    loads('[{"foo": [1, 2]}, {"bar": {"hello": "world"}}, {"code": {"$scope": {}, "$code": "function x() { return 1; }"}}, {"bin": {"$type": "80", "$binary": "AQIDBA=="}}]')
    
    # >>> [{u'foo': [1, 2]}, {u'bar': {u'hello': u'world'}}, {u'code': Code('function x() { return 1; }', {})}, {u'bin': Binary('...', 128)}]
    

    Serialization:

    from bson import Binary, Code
    from bson.json_util import dumps
    dumps([{'foo': [1, 2]},
           {'bar': {'hello': 'world'}},
           {'code': Code("function x() { return 1; }", {})},
           {'bin': Binary(b"")}])
    
    # >>> '[{"foo": [1, 2]}, {"bar": {"hello": "world"}}, {"code": {"$code": "function x() { return 1; }", "$scope": {}}}, {"bin": {"$binary": "AQIDBA==", "$type": "00"}}]'
    

    When the object you try to serialize/deserialize is BSON you need to use mongo's dumps and loads or it won't be parsed correctly. When it is a regular JSON you can use either one you like.