Jodo
Jodo

Reputation: 4763

RESTful-Flask parsing JSON Arrays with parse_args()

This's my code:

parser = reqparse.RequestParser(bundle_errors=True)    
parser.add_argument('list', type=list, location="json")

class Example(Resource):
    def post(self):
        #json_data = request.get_json(force=True)
        json_data = parser.parse_args()
        return json_data

If I post a JSON object like this:

{
  "list" : ["ele1", "ele2", "ele3"]
}

parser.parse_args() parses it to this python list:

'list': ['e','l','e','1']

request.get_json() works, but I would really like to have the validation of the reqparser... How can I get the parser.parse_args() working properly with JSON arrays?

(I get this error: TypeError("'int' object is not iterable",) is not JSON serializable, if if the JSON array contains integers: 'list': [1, 2, 3])

Upvotes: 4

Views: 11562

Answers (2)

tokenizer_fsj
tokenizer_fsj

Reputation: 1240

chuong nguyen is right in his comment to your question. With an example:

def post(self):
    parser = reqparse.RequestParser()
    parser.add_argument('options', action='append')
    parser = parser.parse_args()
    options = parser['options']

    response = {'options': options}
    return jsonify(response)

With this, if you request:

curl -H 'Content-type: application/json' -X POST -d '{"options": ["option_1", "option_2"]}' http://127.0.0.1:8080/my-endpoint

The response would be:

{
    "options": [
      "option_1",
      "option_2"
    ]
}

Upvotes: 7

Jodo
Jodo

Reputation: 4763

Here is a workaround a came up with. But it really seems like a big hack to me...

By extending the input types you can create your own "array type" like that:

from flask import request

def arrayType(value, name):
    full_json_data = request.get_json()
    my_list = full_json_data[name]
    if(not isinstance(my_list, (list))):
        raise ValueError("The parameter " + name + " is not a valid array")
    return my_list

and than use it with the parser:

parser = reqparse.RequestParser(bundle_errors=True)
parser.add_argument('list', type=arrayType, location="json")

It works, but I think there should be a proper way to do this within flaks-restful. I imagine calling request.get_json() for each JSON array is also not the best in terms of performance, especially if the request data is rather big.

Upvotes: 0

Related Questions