I have a python script as below that gather some stores' informations using google API :
import json
import requests
import time
from config import API_KEY, PLACES_ENDPOINT
def getPlaces(lat, lng, radius, keyword, token=None, places=None):
# Building my API call
params = {
'location': str(lat) + ',' + str(lng),
'radius': radius,
'keyword': keyword,
'key': API_KEY
}
if token is not None:
params.update({'pagetoken': token})
r = requests.get(PLACES_ENDPOINT, params=params)
# If its the first time the function is called, then we create the list variable
if places is None:
places = []
for item in r.json()['results']:
# adding element to my list 'places'
places.append(item['name'])
# if there is more results to gather from the next page, call the func again
if 'next_page_token' in r.json():
token = r.json()['next_page_token']
time.sleep(2)
getPlaces(lat, lng, radius, keyword, token, places)
else:
print(json.dumps(places)) # print all the data collected
return json.dumps(places) # return None
Why the returned json places
is None
whereas the data appears as it should be in the final print
?
To fix my issues I just had to get rid of the else statement. As the function is recursive, it won't proceed to the return until it ends looping :
import json
import requests
import time
from config import API_KEY, PLACES_ENDPOINT
def getPlaces(lat, lng, radius, keyword, token=None, places=None):
params = {
'location': str(lat) + ',' + str(lng),
'radius': radius,
'keyword': keyword,
'key': API_KEY
}
if token is not None:
params.update({'pagetoken': token})
r = requests.get(PLACES_ENDPOINT, params=params)
# parsing json
if places is None:
places = []
for item in r.json()['results']:
places.append(item['name'])
if 'next_page_token' in r.json():
token = r.json()['next_page_token']
time.sleep(2)
getPlaces(lat, lng, radius, keyword, token, places)
return json.dumps(places)
Thanks Michael Butscher for the hint !