2

I want to check if the request has provided the required headers using Flask-RestPlus.

I tried using the https://flask-restful.readthedocs.io/en/0.3.5/reqparse.html which I used before to check the body for required parameters and it works but I need to also check for headers

        def RequestParser():
            parser = reqparse.RequestParser()
            parser.add_argument('PaymentMethod', location='headers')
            return parser

        @api.route('/request')
        class Request(Resource):
            parser = RequestParser()
            def post(self):
                data = self.parser.parse_args()
                paymentMethod = request.headers.get('PaymentMethod')
                paymentEndpoint = request.headers.get('PaymentEndpoint')
                return paymentMethod

I am expecting that the result will tell me that there is missing headers needed the same result when there are missing parameters in the body.

Reub
  • 121
  • 2
  • 13

2 Answers2

2

try add argument required:

parser.add_argument('PaymentMethod', required=True, location='headers')

Refer at: https://flask-restful.readthedocs.io/en/0.3.5/reqparse.html#required-arguments

Chien Nguyen
  • 648
  • 5
  • 7
  • I agree, as a side note, here is a working code in the [restplus github](https://github.com/noirbizarre/flask-restplus/issues/398#issuecomment-414951836) that shows the output. It talks about the swagger but the code presented in this issue should also be useful for your problem – IMCoins Jan 24 '19 at 07:49
0

I used expect decorator with parser which checks user_id header.

app = Flask(__name__)
api = Api(app, authorizations=authorizations, security=[{"browser": ["ui"]}])


# Swagger namespaces - in Java they are controllers.
word_count_ns = api.namespace(name='Word count', path='/', description='Word count')


user_id_header_parser = api.parser()
user_id_header_parser.add_argument('user_id', location='headers')


@api.expect(user_id_header_parser)
@word_count_ns.route(api_word_count)
class WordCounter(Resource):
    def post(self):
        """Counts words in request text. Expects header user_id"""

        user_input = request.data.decode()
        user_id_header = request.headers.get('user_id')
        if not check_exists_by_id(user_id_header):
            return Response('user_id header is needed', 401)
        
        return return Response('[]', mimetype='application/json;charset=UTF-8')

Result enter image description here

Yan Khonski
  • 12,225
  • 15
  • 76
  • 114