superasperatus
superasperatus

Reputation: 113

Loop through API json responses and add them into one python dictionary

I want to use the OpenPageRank API to get the 'page rank'and other stats from a list of domains.

Their documentation is in php and I'm having a tough time translating it, or getting it to work in my case.

The idea is to get the API responses and append them to a python dict or a .json file.

At the moment I have this function defined:

    headers = {'API-OPR': '%s' % opr_api_key}
    api_results = {}
    for items in domains_to_check:
        url = 'https://openpagerank.com/api/v1.0/getPageRank?domains%5B0%5D=' + items
        request = requests.get(url, headers=headers)
        api_result = request.json()

The domains_to_check list is already predefined and it contains domains for a test.

Now as you can see above the code sends the request to the OPR and gets the json result it stores into the api_result and as expected it just adds the last API result.

I want to loop through all the domains in the list, send the request and append it to the results.

dict.append[result] doesn't work because the result is a .json file. Not a python dict.

I've tried transforming the result into the Python dict, but failed.

The API documentation hints that an array can be sent via API from a single request but failed to replicate this code from php.

Not sure how to solve this. Or how to approach it. Seems simple enough, but I just can't break it.

Any help welcomed.

Upvotes: 1

Views: 2179

Answers (1)

pbn
pbn

Reputation: 2706

Consider using a list since you are not mentioning associating results with any key.

def send_domains_to_OPR():
    headers = {'API-OPR': '%s' % opr_api_key}
    api_results = []
    for items in domains_to_check:
        url = 'https://openpagerank.com/api/v1.0/getPageRank?domains%5B0%5D=' + items
        request = requests.get(url, headers=headers)
        api_results.append(request.json())

If you want to match response with a list of domains to check you can always zip them:

for items, response in zip(domains_to_check, api_results):
  print(items)
  print(response)

Upvotes: 2

Related Questions