Akbarsha
Akbarsha

Reputation: 2568

How to return a response with multiple marshal_with() in flask_restplus?

Following is flask_restplus response call for PUT verb

@api.doc('update a franchise by id')
    @api.expect(create_item_fields, validate=True)
    @api.marshal_with(success_fields)
    def put(self, fid):
        franchise = FranchiseModel.query.filter_by(id=fid).first()
        if franchise:
            is_success, result = FranchiseModel.update_franchise(
                franchise, api.payload)
            if is_success:
                return {'success': True, 'message': 'Franchise has been updated', 'data': result}, 200
            else:
                raise CouldNotUpdateFranchise(str(result))

@api.errorhandler(CouldNotUpdateFranchise)
    @api.marshal_with(error_fields)
    def return_error(error):
        return {'success': False, 'message': str(error)}, 400

I'm making use of the @api.errorhandler But I don't know how to return multiple response format with marshal_with

Upvotes: 1

Views: 2181

Answers (1)

Cedric
Cedric

Reputation: 446

EDIT: Ok old answer just lists it as a valid response in Swagger.

But with this article https://github.com/noirbizarre/flask-restplus/issues/559 I still got the solution:

from flask_restplus import marshal
# I call API 'foo' and my Namespace 'bar'
another = foo.model('For 200', {'Another': fields.Integer()})
success = foo.model('For 201', {'Success': fields.Integer()})

@bar.route('/test/<int:id>')
class Test(Resource):
    @bar.response(model=another, code=200)
    @bar.response(model=success, code=201)
    def get(self, id):
        if id == 200:
             return marshal({'Another': 200}, another), 200
        elif id == 201:
             return marshal({'Success': 201}, success), 201

Upvotes: 4

Related Questions