7

I am using Flask Restful for my server API and am posting to the server a dictionary where one of the values is a list of dictionary's.

parser.add_argument('products_in_basket', type=list)
def post(self, user_id):
   args = parser.parse_args()
   print request.data
   print args['my_list']

The problem I have is args['my_list'] is only returning the first element of the list. Whereas I can see all list from request.data.

This is request.data

{"address_id":1,"my_list":[{"size":12,"colour":"red","id":34219,"quantity":1},{"size":10,"colour":"red","id":12219,"quantity":2},{"size":8,"colour":"red","id":5214,"quantity":3}],"payment_card_id":1}

This is args['my_list']

[u'colour', u'quantity', u'id', u'size']

Where am I going wrong?

3 Answers3

12

What are your parser add_argument options? Is products_in_basket an actual key to the data that is requested? Or are you trying to provide an arbitrary name and/or rename the dict?

Take a look at Multiple Values & Lists from the Request Parsing documentation.

You may want to be doing something like this instead...

parser = reqparse.RequestParser()
parser.add_argument('my_list', action='append')
siegerts
  • 461
  • 4
  • 11
1

Try accessing the data like this:

for product in args.my_list:
        size = product.get('size')
        etc....

This will allow you to iterate over all the dict objects in the my_list list.

Matt Healy
  • 18,033
  • 4
  • 56
  • 56
1

You can use the location parameter in the add_argument function. This will specify that you are working with json and it will append the others elements in the list.

parser = reqparse.RequestParser()
parser.add_argument('my_list', location='json')
Kofi Nartey
  • 2,529
  • 2
  • 9
  • 5
  • This was the solution for me. Without it, if I passed a single value in a list, it would appear like this : [['v','a','l','u','e']] – Samuurai Apr 14 '23 at 18:07