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 = ""+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)
print("Results for type "+type)

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

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

return results

# Get the rest of the results

def getNextPlace(page_token,APIKEY):


next_url = '' + page_token + '&key=' + APIKEY

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

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

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

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 = ''+location+"&radius="+radius+"&type="+type+"&key="+APIKEY + "&pagetoken=" + page_token + "&key=" + APIKEY