flaskmarshmallowwebargs

How to integrate webargs + marshmallow?


I am only beginner in flask. Trying to integrate marshmallow and webargs. It perfectly works in flask-restful Resource class. But when I use a simple flask route it does not work

routes.py

class UserAPI(Resource):
    @use_args(UserSchema())
    def post(self, *args):
        print(args)
        return 'success', 201

    def get(self):
        return '<h1>Hello</h1>'


@bp.route('/test/', methods=['POST'])
@use_kwargs(UserSchema())
def test2(*args, **kwargs):
    print(args)
    print(kwargs)
    return 'success', 201


api.add_resource(UserAPI, '/', endpoint='user')

I've added error handler which is necessary when using use_args

from webargs.flaskparser import parser, abort
from webargs import core


@parser.error_handler
def webargs_validation_handler(error, req, schema, *, error_status_code, error_headers):
    status_code = error_status_code or core.DEFAULT_VALIDATION_STATUS
    abort(
        400,
        exc=error,
        messages=error.messages,
    )

That's what I'm getting when I make request to Resource endpoint what is normal enter image description here

And that's what I'm getting when I make request to a simple flask route what is not normal

enter image description here

I want to be able to use both ways


Solution

  • Found answer in webargs docs :) https://webargs.readthedocs.io/en/latest/framework_support.html#error-handling

    from flask import jsonify
    
    
    # Return validation errors as JSON
    @app.errorhandler(422)
    @app.errorhandler(400)
    def handle_error(err):
        headers = err.data.get("headers", None)
        messages = err.data.get("messages", ["Invalid request."])
        if headers:
            return jsonify({"errors": messages}), err.code, headers
        else:
            return jsonify({"errors": messages}), err.code