0

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 ?

2
  • 2
    if 'next_page_token' in r.json() if this is true, it returns None because no explicit return is given. Commented Jun 25, 2020 at 11:19
  • Indeed, I've removed my else statement and it now works like a charm - thanks ! Commented Jun 25, 2020 at 11:22

1 Answer 1

1

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 !

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.