Adam P
Adam P

Reputation: 382

Loop through JSON content posted to Flask app

I'm trying to post JSON data to a flask application. The app is then supposed to loop through each object in the array and return the results. If i have just one object in the array I'm able to return the results for each value in the object. But any JSON data with more than one object gives a 500 Internal Server error.

What am I missing here?

            from flask import Flask, url_for
            app = Flask(__name__)
            from flask import request
            from flask import json

            @app.route('/messages', methods = ['POST'])
            def api_message():

                if request.headers['Content-Type'] == 'application/json':
                    foo = request.get_json()
                    output = ""
                    for i in foo['Location']:
                      Item_id = i['Item_id']
                      Price = i['Price']
                      output = output + Item_id + Price
                      # do stuff here later
                    return output
                else:
                    return "415 Unsupported"


            if __name__ == '__main__':
                app.run()

I run the above code in one terminal, and I get "500 Internal Server error" when I post the JSON data in another terminal with:

            curl -H "Content-type: application/json" \ -X POST http://127.0.0.1:5000/messages -d '[{"Location":"1","Item_id":"12345","Price":"$1.99","Text":"ABCDEFG"},{"Location":"2","Item_id":"56489","Price":"$100.99","Text":"HIJKLMNO"},{"Location":"3","Item_id":"101112","Price":"$100,000.99","Text":"PQRST"}]'

Upvotes: 1

Views: 5351

Answers (2)

iFlo
iFlo

Reputation: 1484

Actually, with this code :

for i in foo['Location']:
    Item_id = i['Item_id']
    Price = i['Price']
    output = output + Item_id + Price
    # do stuff here later

You are saying that the first element you get is a location object. In fact, when you have multiple object, the first element you get is a list of location element. So you have to perform a loop on this list before using your location objects.

for location_object in foo :
    for i in location_object["Location"] :
        Item_id = i['Item_id']
        Price = i['Price']
        output = output + Item_id + Price
        # do stuff here later

Upvotes: 1

furas
furas

Reputation: 142641

You have list so you need

for i in foo:
    print(i['Location'])
    print(i['Item_id')
    print(i['Price'])
    print(i['Text'])

BTW: next time run in debug mode

app.run(debug=True)

and you see more information on web page.

Upvotes: 4

Related Questions