Home > OS >  Flask: Jsonify response, then use response to call a third-party API - how to?
Flask: Jsonify response, then use response to call a third-party API - how to?

Time:10-25

I have a Flask app. The app sends a JSON file to the server where it is parsed using jsonify. The newly parsed object is then used to call a third-party API. I struggle with the setup as I don't seem to be able to call the third-party API from within the function, using the jsonified response object.

My parsing function

@site.route('/data', methods=['POST']) 
def parse_request(): 
    data = request.get_json()
    print(data)
    return jsonify(success=True)
    buy(data)

print(data) looks like this:

data = [{'id': '001', 'product': 'Tshirt', 'price': '9.99', 'quantity': '1'}, {'id': '002', 'product': 'Trousers', 'price': '19.99', 'quantity': '3'}, {'id': '003', 'product': 'Jacket', 'price': '29.99', 'quantity': '2'}]

If I move buy(data) above the return statement, I get the following error: AttributeError: 'list' object has no attribute 'keys'.

Calling the third-party API:

def buy(data):
    for key in data.keys():
      id = data[key]['id']
      quantity = data[key]['quantity']

      
      api.submit_order(
        product=product,
        quantity=quantity
      print((f"Submitted order for {quantity} piece(s) of {product}(s)"))
    return

Depending on where I call buy(data) in parse_request(), I either get the attribute error or nothing happens. What am I doing wrong?

CodePudding user response:

Data is a list of dict objects. You can just iterate over it with for item in data.
The keys attribute is necessary if you want to iterate over the keys of a dict.

def buy(data):
    for item in data:
        id = item['id']
        quantity = item['quantity']

        api.submit_order(
            product=product,
            quantity=quantity
        )
        print(f"Submitted order for {quantity} piece(s) of {product}(s)")
    return

CodePudding user response:

If I move buy(data) above the return statement, I get the following error

That attribute error will only trigger when buy(data) is above return, because once the return statement is reached within a function, nothing after that is executed.

# This just returns 'a':
def fn():
    return 'a'
    print ('b')

# On the other hand, this prints 'b', then returns 'a'
def fn2():
    print ('b')
    return 'a'

With that in mind, as for the actual error:

`AttributeError: 'list' object has no attribute 'keys'.`

Lists types don't have a key attribute (only dictionaries do). Remember data is a list of dictionaries.

I think you want something more like:

def buy(data):
    for row in data:
        product = row['product']
        quantity = row['quantity']      
        api.submit_order(
            product=product,
            quantity=quantity )
        print((f"Submitted order for {quantity} piece(s) of {product}(s)"))
    return
  • Related