2

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

  • What are you asking? You should review [How to ask a question](https://stackoverflow.com/help/how-to-ask) and reform your post. Not only do you need to ask a direct and pointed question on a specific item, you need to show how you already tried to solve the problem. – Chase Dec 03 '18 at 05:08
  • I've searched on google for some using the same keywords. Tried the method use in https://stackoverflow.com/questions/30779584/flask-restful-passing-parameters-to-get-request. It does not work for my case. – Jian Kai Wong Dec 03 '18 at 06:21
  • @Chase I've edited the post a little, I don't know if it will help you understand more on what I'm trying to do. – Jian Kai Wong Dec 03 '18 at 06:27
  • [reqparse is deprecated, by the way](https://flask-restful.readthedocs.io/en/latest/reqparse.html) – OneCricketeer Dec 03 '18 at 06:43

1 Answers1

2

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']})
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • This method seems to work. It's just that I other parties need to use json.dumps on the parameter. I didn't think its this simple. Thanks. – Jian Kai Wong Dec 03 '18 at 10:23
  • You might also be able to iterate over a form, but I almost always use JSON over HTTP nowadays. And whether you `json.dumps` or not, depends on http client. Requests will allow you to be able to make calls using `json=` parameter – OneCricketeer Dec 03 '18 at 14:17
  • 1
    Yes! I was able to get what I want using `request.form.to_dict()`, there will be no need to use `json.dumps` in the parameter with this. – Jian Kai Wong Dec 05 '18 at 06:25