JohnA JohnA - 1 month ago 19
Python Question

Error when using Requests with python 3.5 recursively (GooglePlaces API)

I have been having a problem where I try to send a get request and if there is a next page token in the result it will then take that link and execute another request recursively until there is no next page token in the result.
The first request works fine but when there is a next page token in the response and it tries to execute the new request the result is an Invalid ReSponse but if I take the link that was given from the result and use it in postman or on my browser everything is fine.
I'm assuming it has something to requests running on different threads at the same time.

Here is what I have:

import requests

def getPlaces(location,radius,type, APIKEY):

url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="+location+"&radius="+radius+"&type="+type+"&key="+APIKEY

print('Getting results for type ' + type + '...')

r = requests.get(url)

response = r.json()

results = []

if response['status'] == 'ZERO_RESULTS':
print("Did not find results for the type "+type)
else:
print("Results for type "+type)

for result in response['results']:
results.append(result)
print(result)
print('Printing results')
print(results)

if 'next_page_token' in response:
print("There is a next page")
page_token = response['next_page_token']
print(page_token)
next_results = getNextPlace(page_token,APIKEY)
print(next_results)
results.append(next_results)

return results

# Get the rest of the results


def getNextPlace(page_token,APIKEY):

print('...')

next_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?pagetoken=' + page_token + '&key=' + APIKEY

print(next_url)
r = requests.get(next_url)
response = r.json()
results = []
print(response)

if response['status'] == 'ZERO_RESULTS':
print("Did not find results")
elif response['status'] == 'INVALID_REQUEST':
print('Invalid response')
else:
for next_result in response['results']:
results.append(next_result)
print(next_result)

if 'next_page_token' in response:
new_page_token = response['next_page_token']
getNext = getNextPlace(new_page_token,APIKEY)
results.append(getNext)

return results

Answer Source

Your code print "invalid response" because response['status'] == 'INVALID_REQUEST', so it is google api service think your url request is invalid.

As this document says, the parameter location, radius, type and key is required, and the pagetoken is optional. So your second request url is invalid because it does not have the all required key.

Maybe you should try change the url to :

next_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location='+location+"&radius="+radius+"&type="+type+"&key="+APIKEY + "&pagetoken=" + page_token + "&key=" + APIKEY