Jian Kai Wong
Jian Kai Wong

Reputation: 23

Flask restful: dynamical parameter with POST

I would like to parse a dynamical set of arguments to the API. The number of arguments is not fixed as the one calling the API is another party. I would like to make it so that my API will be able to accept the additional argument and also include it should there be any changes done by the other side in the future.

I want to change this:

class PaymentReceive(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('arg1', type=str, location="form")
        parser.add_argument('arg2', type=str, location="form")
        args = parser.parse_args()

To something like this:

class PaymentReceive(Resource):
    def post(self):
        parsers = reqparse.RequestParser()
        for key, value in parsers.items():
            parser.add_argument(key, type=str, location="form")

        args = parser.parse_args()

I tried the method in here to no avail. Please help

Upvotes: 2

Views: 1392

Answers (1)

OneCricketeer
OneCricketeer

Reputation: 191728

If you want to parse some dynamic set of values, then you should just accept a raw JSON payload, which you can iterate and unmarshal however you wish.

In plain Flask,

@app.route('/payment', methods=['POST'])
def receive_payment():
    content = request.json
    for k, v in content.items():
        print(k, v)
    # return some received id
    return jsonify({"payment_id":content['payment_id']})

Upvotes: 2

Related Questions