Skip to content
Advertisement

Python – save multiple responses from multiple requests

I am pulling JSON data from an api and I am looking to pass in a different parameter for each request and save each response

My current code

# create an empty list to store each account id 
accounts = []
##store in accounts list every id
for each in allAccounts['data']:
    accounts.append((each['id']))


#for each account , call a new account id for the url
for id in accounts:
    urlAccounts = 'https://example.somewebsite.ie:000/v12345/accounts/'+id+'/users'

I save a response and print out the values.

accountReq = requests.get(urlAccounts, headers=headers)
allUsers = accountReq.json()

for each in allUsers['data']:
    print(each['username']," " +each['first_name'])

This is fine and it works but I only store the first ID’s response.

How do I store the responses from all of the requests? So I’m looking to send multiple requests where the ID changes every time and save each response essentially.

I’m using python version 3.10.4 .

Advertisement

Answer

My code for this in case anyone stumbles across this.

# list of each api url to use
link =[]
#for every id in the accounts , create a new url link into the link list
for i in accounts:
    link.append('https://example.somewebsite.ie:000/v12345/accounts/'+i+'/users')

#create a list with all the different requests
accountReq = []
for i in link:
    accountReq.append(requests.get(i, headers=headers).json())

# write to a txt file
with open('masterSheet.txt', 'x') as f:
    #for every request
    for each in accountReq:
        #get each accounts data
        account = each['data']
        #for each accounts data
        #get each users email and names
        for data in account:
                sheet=(data['username']+" "+" ",data['first_name'],data['last_name'])
                f.write(str(sheet)+"n")
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement