j doe j doe - 8 months ago 29
Python Question

How to use a for loop to iterate through an array

So basically I am getting a list of ids and storing them in an array ids. I want to use these ids to do api calls. Here is my code:

url = "https://swag.com"
headers = {'x-api-token': "cool"}
response = requests.get(url, headers=headers)
data = json.loads(response.text)

ids = [element['id'] for element in data['result']['elements']]
for i in ids:
url_2 = "https://swag.com/"
survey_url = url_2 + str(ids)

response_2 = requests.get(survey_url, headers=headers)
data_2 = json.loads(response_2.text)

so basically I don't know how to separate the ids to run individual calls. How would I go about doing this. With my code it just tries to run all ids as 1 api call.


Your for loop is constructing a survey url based on ids instead of id.

Change it to

for i in ids:
    url2 = "https://swag.com/"
    # your mistake was using str(ids) here.
    survey_url = url_2 + str(i)
    # proceed further with making the request for this survey url
    # Also, I feel the response_2, data_2 and print(response_2.text)
    # should be inside this for loop

An easy way to catch this error would be to put a print statement and print your survey_url.