-
Notifications
You must be signed in to change notification settings - Fork 1
/
ziptastic.py
67 lines (48 loc) · 1.97 KB
/
ziptastic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import requests
class ZiptasticAPIKeyRequiredException(Exception):
pass
class Ziptastic(object):
"""Ziptastic Python Module"""
#: The current endpoint where Ziptastic APIs are served from.
endpoint = 'zip.getziptastic.com'
def __init__(self, api_key):
"""
Initialize Ziptastic API
:param: This is your Ziptastic API Key that you can get from
https://www.getziptastic.com/dashboard
"""
self.api_key = api_key
@staticmethod
def build_url(endpoint, version='v3', preferred_protocol='https'):
"""Build the Ziptastic API url."""
return preferred_protocol + '://' + endpoint + '/' + version
def get_from_postal_code(self, postal_code, country='US'):
"""Get geo data from postal code and country code"""
headers = {}
#: If no api_key is set then default to Version 2 of Ziptastic API.
if self.api_key:
headers.update({
"x-key": self.api_key
})
uri = self.build_url(self.endpoint)
else:
uri = self.build_url(self.endpoint, version='v2')
url = "{uri}/{country}/{postal_code}".format(uri=uri, country=country,
postal_code=postal_code)
r = requests.get(url, headers=headers)
return r.json()
def get_from_coordinates(self, latitude, longitude):
"""Get geo data from coordinates"""
headers = {}
#: If no api_key is set then default to Version 2 of Ziptastic API.
if self.api_key:
headers.update({
"x-key": self.api_key
})
uri = self.build_url(self.endpoint)
else:
raise ZiptasticAPIKeyRequiredException
url = "{uri}/{latitude}/{longitude}".format(uri=uri, latitude=latitude,
longitude=longitude)
r = requests.get(url, headers=headers)
return r.json()