Skip to content

Instantly share code, notes, and snippets.

@madagra
Created December 21, 2017 19:24
Show Gist options
  • Save madagra/6f70c8dbaf98ccc2043fc86034df4987 to your computer and use it in GitHub Desktop.
Save madagra/6f70c8dbaf98ccc2043fc86034df4987 to your computer and use it in GitHub Desktop.
Simple Python wrapper for the Google Places API
import requests
import unittest
from urllib.parse import urlencode
class CheckResponse :
def __call__(self,fn) :
def fn_wrapper(*args) :
try :
response = fn(*args)
if "status" not in response or \
response["status"] != "OK" or \
len(response["results"]) == 0 :
msg = """
Error in calling the Place API.
Type: {}
Parameters: {}
Status: {}
""".format(args[1],
args[2],
response["status"] if "status" in response else "NO STATUS")
raise Exception(msg)
return response
except Exception as ex :
print(ex)
return fn_wrapper
class PlaceAPI :
base_url = "https://maps.googleapis.com/maps/api/place/"
def __init__(self,key=None,fmt="json") :
if key is None :
raise Exception("A Google Place API key is required")
self.key = key
self.fmt = fmt
self.session = requests.Session()
@CheckResponse()
def _call(self,type_,params) :
url = ""
if type_ == "textsearch" :
url = PlaceAPI.base_url + "textsearch/"
elif type_ == "nearbysearch" :
url = PlaceAPI.base_url + "nearbysearch/"
url += "{}".format(self.fmt)
params['key'] = self.key
url = url + "?" + urlencode(params)
response = self.session.get(url=url).json()
return response
def textsearch(self,params) :
if "query" not in params :
raise Exception("A query must be specified!")
return self._call("textsearch",params)
def nearbysearch(self,params) :
if "location" not in params or "radius" not in params:
raise Exception("Both radius and location must be specified!")
return self._call("nearbysearch",params)
def close(self) :
self.session.close()
#### TESTS ####
class PlaceAPITest(unittest.TestCase) :
def setUp(self) :
key = None # here set your own key to test
self.api = PlaceAPI(key=key)
def test_textsearch(self) :
params = {
"query" : "Borgiallo"
}
self.api.textsearch(params)
def test_nearbysearch(self) :
params = {
"location" : "-33.8670522,151.1957362",
"radius" : 500,
"type" : "restaurant"
}
self.api.nearbysearch(params)
def tearDown(self) :
self.api.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment