Forums

Google Maps Geolocate API call returns invalidRequest on pythonanywhere but not locally

I have a Django site that works without issue when run on the Django dev server on my local machine. When I try to run the site on my pythonanywhere account, everything works except for a single call to the Google Maps Geolocation API.

The function call that is failing is:

def geolocate():
    url = "https://www.googleapis.com/geolocation/v1/geolocate?key=%s" % API_KEY
    r = requests.post(url)
    lat_lng = r.json()['location']
    return (lat_lng['lat'], lat_lng['lng'])

The response that I get back from the requests.post() call when run on pythonanywhere is:

{
"error": {
  "errors": [
   {
    "domain": "geolocation",
    "reason": "invalidRequest",
    "message": "Bad Request"
   }
  ],
  "code": 400,
  "message": "Bad Request"
 }
}

Whereas when I run it on the dev server I get:

{
 "location": {
  "lat": 39.9546734,
  "lng": -96.5985613
 },
 "accuracy": 2678.0
}

which is the response I am looking for.

I have also tried making the request with curl on both my local machine, and from a pythonanywhere bash console. Using this command:

curl 'https://www.googleapis.com/geolocation/v1/geolocate?key=MY_API_KEY' -H "Content-Type: application/json" -d {}

I get the same 400 response from pythonanywhere, but get the expected location data on my local machine. .googleapis.com is among the whitelisted domains for pythonanywhere, and my Django site on pythonanywhere makes calls to the Google Maps Geocode and Places APIs in JavaScript and in calls to web services without any issue. It seems to just be an issue with the Geolocate API.

One other potentially useful piece of information: when I use the -v flag with curl to get more verbose output, I see that when I make the "Bad Request" on pythonanywhere I get the line:

* Server GSE is not blacklisted

which I do not see when I run the command locally. I have done some searching and cannot figure out what that means or if it is relevant, but it stood out so I thought I would mention in case it raises flags for more knowledgeable users.

I have seen this question, and this question, as well as a number of seemingly related, but have not been able to solve my issue so far. I have posted an almost identical question on StackOverflow, but I wanted to post here as well, since the issue is potentially site-specific. Any advice would be appreciated. Thank you!

Sending an empty request body to google geolocation amounts to "tell me where this machine is". I think that Google is smart enough to know that trying to get the location of an AWS instance is not meaningful.