How do I call api based on two lists ?
Have two lists, states
and counties
. Using these lists to call and get some_results
. But AK
item in states
list doesn't have counties
as responses so it should just skips it. But when I tried to debug it with:
print("requests.get('https://represent.opennorth.ca/states/{0}/counties/{1}/area_codes'.format(states, counties))")
I noticed that the loop inserted the entire lists instead of one by one item in the list: >> requests.get('https://represent.opennorth.ca/states/[AK, GA, NY]/counties/[gwinneth, duluth, manhattan, bronx]/area_codes'
How do I solve this?
states = [AK, GA, NY]
counties = [gwinneth, duluth, manhattan, bronx]
some_results = []
for county in counties:
rr = requests.get('https://represent.opennorth.ca/states/{0}/counties/{1}/area_codes'.format(states, counties))
if rr.status_code == 200:
some_results.append(rr.json())
else:
print("Request to {} failed".format(states, counties))
CodePudding user response:
Please try this code. also read the comments.
import requests
# suppose these are all string variables defined elsewhere
states = [AK, GA, NY] # why not [GA, NY]?
counties = [gwinneth, duluth, manhattan, bronx]
some_results = []
for state in states:
for county in counties:
# you should only pass single string here, never list
url = f'https://represent.opennorth.ca/states/{state}/counties/{county}/area_codes'
resp = requests.get(url)
if resp.status_code == 200:
some_results.append(resp.json())
else:
print(f"Request to {state} {county} failed")
print(resp.status_code)
print(resp.reason)
print(resp.text)