I\'m building and API on top of Flask using marshmallow and mongoengine. When I make a call and an ID is supposed to be serialized I receive the following error:
You can extend the fields.Field class to create your own field. Here's how marshmallow-mongoengine (mentioned in another answer) implements this:
import bson
from marshmallow import ValidationError, fields, missing
class ObjectId(fields.Field):
def _deserialize(self, value, attr, data):
try:
return bson.ObjectId(value)
except Exception:
raise ValidationError("invalid ObjectId `%s`" % value)
def _serialize(self, value, attr, obj):
if value is None:
return missing
return str(value)
and then:
class MySchema(Schema):
id = ObjectId()
(I found this useful when not using MongoEngine, just using pymongo)