Reputation: 351
So I have this list which stores different request URLS for finding an account.
accounts= []
Each url looks something like this.
'https://example.somewebsite.ie:000/v12345/accounts/12345/users'
Each URL has a different ID so the next URL in the list would be for example
'https://example.somewebsite.ie:000/v12345/accounts/54321/users'
I've tried doing something like this.
accountReq = []
for i in accounts:
accountReq = requests.get(i, headers=headers).json()
for each in accountReq['data']:
print(each['username']+" "+" ",each['first_name'],each['last_name'])
This only prints out the last GET requests data.
How do I write multiple requests based on taking each different value in my list?
I can do separate requests line by line but I don't want to do this as I may have a 100 plus URLS to try.
Upvotes: 1
Views: 586
Reputation: 969
accountReq
only holds the last data because you're redefining the variable on each iteration. You should change your code to this:
accountReq = []
for i in accounts:
accountReq.append(requests.get(i, headers=headers).json())
for each in accountReq:
account = each['data']
for data in account:
print(data['username']+" "+" ",data['first_name'],data['last_name'])
Now this will ADD every individual JSON object data to accountReq
list.
Upvotes: 1
Reputation: 27211
If you're only interested in printing certain values then:
accounts = [] # a list of URLs
for account in accounts:
(r := requests.get(account, headers=headers)).raise_for_status()
for d in r.json()['data']:
print(f"{d['username']}, {d['first_name']}, {d['last_name']}")
Upvotes: 1
Reputation: 351
for each in accountReq:
account = each['data']
for data in account:
print(data['username']+" "+" ",data['first_name'],data['last_name'])
that's what I done after tweaking an answer someone provided.
Upvotes: 0