Serialize and validate SQLAlchemy models to/from JSON with Marshmallow schemas.
Serialization with Marshmallow
pip install flask-marshmallow marshmallow-sqlalchemy
from flask_marshmallow import Marshmallow
ma = Marshmallow(app)
class UserSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = User
load_instance = True
exclude = ("password",)
email = ma.auto_field(validate=validate.Email())
user_schema = UserSchema()
users_schema = UserSchema(many=True)
# Serialize
user_schema.dump(user) # object → dict
users_schema.dump(users)
# Deserialize and validate
try:
user = user_schema.load(request.json) # dict → User object
except ValidationError as err:
return jsonify(err.messages), 422
# In route
@api.route("/users/<int:id>")
def get_user(id):
user = db.get_or_404(User, id)
return jsonify(user_schema.dump(user))