Getting key error: 'groups' in python when implementing foursquare api

129 Views Asked by At

I am getting keyerror: 'groups' when trying to fetch nearby venues using Foursquare API. Following is my code:

Any help would really be appreciated. Thank you.

def getNearbyVenues(names, latitudes, longitudes, radius = 1200):
    
    venues_list=[]
    for name, lat, lng in zip(names, latitudes, longitudes):   
        url = 'https://api.foursquare.com/v2/venues/explore?&client_id={}&client_secret={}&v={}&ll={},{}&radius={}&limit={}'.format(
            CLIENT_ID, 
            CLIENT_SECRET, 
            VERSION, 
            lat, 
            lng, 
            radius, 
            LIMIT)
            
        results = requests.get(url).json()["response"]['groups'][0]['items']
        
        venues_list.append([(
            name, 
            lat, 
            lng, 
            v['venue']['name'], 
            v['venue']['location']['lat'], 
            v['venue']['location']['lng'],  
            v['venue']['categories'][0]['name']) for v in results])

    nearby_venues = pd.DataFrame([item for venue_list in venues_list for item in venue_list])
    nearby_venues.columns = ['City', 
                  'City Latitude', 
                  'City Longitude', 
                  'Venue', 
                  'Venue Latitude', 
                  'Venue Longitude', 
                  'Venue Category']
    
    return(nearby_venues)

texas_venues = getNearbyVenues(names = coords['City'], latitudes = coords['CityLat'], longitudes = coords['CityLong'])
1

There are 1 best solutions below

0
GaryMBloom On

The error you're seeing comes from the line:

results = requests.get(url).json()["response"]['groups'][0]['items']

which takes the return of the json() call, which is a dictionary. It then uses the key "response" to extract what it expects to be another dictionary which has a key "groups". But whatever dict is being returned does not have that key, which is why you see that error.

You can break your extraction up into steps to help debug and make your code more robust. Rather than accessing a dict value by key as in d[key], a more fault-tolerant manner is d.get(key), which will return a None if the key is not found (rather than throwing an exception). So you might change the above line from:

results = requests.get(url).json()["response"]['groups'][0]['items']

to:

response_ = requests.get(url).json()["response"]
groups_ = response_.get('groups')
if groups_:
    results = groups_[0].get('items')
    if results:
        "blah blah blah"
else:
    print(f"{groups_=}") # debug-friendly print output
    breakpoint()

Then, when you get your code running the way you want, you can get rid of the extra debug lines...