Skip to content
Advertisement

How to create multiple API requests based on different param values?

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement