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
JavaScript
x
11
11
1
# create an empty list to store each account id
2
accounts = []
3
##store in accounts list every id
4
for each in allAccounts['data']:
5
accounts.append((each['id']))
6
7
8
#for each account , call a new account id for the url
9
for id in accounts:
10
urlAccounts = 'https://example.somewebsite.ie:000/v12345/accounts/'+id+'/users'
11
I save a response and print out the values.
JavaScript
1
6
1
accountReq = requests.get(urlAccounts, headers=headers)
2
allUsers = accountReq.json()
3
4
for each in allUsers['data']:
5
print(each['username']," " +each['first_name'])
6
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.
JavaScript
1
23
23
1
# list of each api url to use
2
link =[]
3
#for every id in the accounts , create a new url link into the link list
4
for i in accounts:
5
link.append('https://example.somewebsite.ie:000/v12345/accounts/'+i+'/users')
6
7
#create a list with all the different requests
8
accountReq = []
9
for i in link:
10
accountReq.append(requests.get(i, headers=headers).json())
11
12
# write to a txt file
13
with open('masterSheet.txt', 'x') as f:
14
#for every request
15
for each in accountReq:
16
#get each accounts data
17
account = each['data']
18
#for each accounts data
19
#get each users email and names
20
for data in account:
21
sheet=(data['username']+" "+" ",data['first_name'],data['last_name'])
22
f.write(str(sheet)+"n")
23