Search code examples
pythonjsondjangoe-commerce

Python consuming API (Printful)


I am struggling to find a way to call on JSON generating from the following code. How for example, Can I call a list of "name" available on the JSON? Ps: don't worry about the Printful secret key; this is a test account.

import json
import requests
import base64

key = 'xk7ov0my-t9vm-70z6:y491-2uyygexkkq6r'
key = base64.b64encode(bytes(key, 'utf-8'))
keyDecoded = key.decode('ascii')
header = {'Authorization': 'Basic ' + keyDecoded}
r = requests.get('https://api.printful.com/sync/products', headers=header)

# packages_json = r.json()

test = r.json()

print(json.dumps(test, indent=4))

# print(test["name"])

Solution

  • If you try to print type of test, you will see that it is a dict:

    print(type(test)) # dict
    print(print(test.keys()) # dict_keys(['code', 'result', 'extra', 'paging'])
    

    Than we need to extract result

    print(type(test["result"])) # <class 'list'>
    print(len(test["result"])) # 3
    print(type(test["result"][0])) # <class 'dict'>
    

    And in this we will extract name from the dict:

    print([n for i in test["result"] for k, n in i.items() if k == "name"])
    

    Output:

    ['Snapback Hat', 'Short-Sleeve Unisex T-Shirt', 'Short-Sleeve Unisex T-Shirt']