Skip to content

Commit 595d753

Browse files
committed
Merge pull request #10 from hbrunn/master-v2
[IMP] support the v2 api
2 parents 9c04bc3 + 5cfee14 commit 595d753

File tree

4 files changed

+82
-79
lines changed

4 files changed

+82
-79
lines changed

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ This API allows you to search for Dutch addresses using zipcodes.
88

99
For more information about this API, please visit http://postcodeapi.nu
1010

11+
This library supports both the v1 and the v2 api, defaulting to v1 for now.
12+
1113

1214
##Installation
1315

@@ -38,6 +40,8 @@ Get the address by using the zipcode and the house number
3840
from pyPostcode import Api
3941

4042
postcodeapi = Api('{YOUR_API_KEY}') # Set your own API-key
43+
# if you want to use the v2 api, say
44+
postcodeapi = Api('{YOUR_API_KEY}', (2, 0, 0))
4145
result = postcodeapi.getaddress('1011AC', 154) # use address search
4246
print result.street, result.house_number, result.town
4347
```

example.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,14 @@
33
postcodeapi = Api('{YOUR_API_KEY}')
44
result_street = postcodeapi.getaddress('1011AC') # use p6 search
55
result_address = postcodeapi.getaddress('1011AC', 154) # use address search
6-
print result_street._data, result_address._data
6+
for result in [result_street, result_address]:
7+
print result.street
8+
print result.house_number
9+
print result.postcode
10+
print result.town
11+
print result.municipality
12+
print result.province
13+
print result.latitude
14+
print result.longitude
15+
print result.x
16+
print result.y

pyPostcode/__init__.py

Lines changed: 66 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
import httplib
1212
import json
13+
import logging
1314

1415

1516
__version__ = '0.1'
@@ -24,13 +25,17 @@ def __init__(self, id, message):
2425

2526
class Api(object):
2627

27-
def __init__(self, api_key):
28+
def __init__(self, api_key, api_version=(1, 0, 0)):
2829
if api_key is None or api_key is '':
2930
raise pyPostcodeException(
3031
0, "Please request an api key on http://postcodeapi.nu")
3132

3233
self.api_key = api_key
33-
self.url = 'api.postcodeapi.nu'
34+
self.api_version = api_version
35+
if api_version >= (2, 0, 0):
36+
self.url = 'postcode-api.apiwise.nl'
37+
else:
38+
self.url = 'api.postcodeapi.nu'
3439

3540
def handleresponseerror(self, status):
3641
if status == 401:
@@ -48,12 +53,18 @@ def request(self, path=None):
4853
'''Helper function for HTTP GET requests to the API'''
4954

5055
headers = {
51-
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
5256
"Accept": "application/json",
5357
"Accept-Language": "en",
54-
"Api-Key": self.api_key}
55-
56-
conn = httplib.HTTPConnection(self.url)
58+
# this is the v1 api
59+
"Api-Key": self.api_key,
60+
# this is the v2 api
61+
"X-Api-Key": self.api_key,
62+
}
63+
64+
if self.api_version >= (2, 0, 0):
65+
conn = httplib.HTTPSConnection(self.url)
66+
else:
67+
conn = httplib.HTTPConnection(self.url)
5768
'''Only GET is supported by the API at this time'''
5869
conn.request('GET', path, None, headers)
5970

@@ -67,21 +78,40 @@ def request(self, path=None):
6778
conn.close()
6879

6980
jsondata = json.loads(resultdata)
70-
data = jsondata['resource']
81+
82+
if self.api_version >= (2, 0, 0):
83+
data = jsondata.get('_embedded', {}).get('addresses', [])
84+
if data:
85+
data = data[0]
86+
else:
87+
data = None
88+
else:
89+
data = jsondata['resource']
7190

7291
return data
7392

7493
def getaddress(self, postcode, house_number=None):
7594
if house_number is None:
7695
house_number = ''
7796

78-
path = '/{0}/{1}'.format(
97+
if self.api_version >= (2, 0, 0):
98+
path = '/v2/addresses/?postcode={0}&number={1}'
99+
else:
100+
path = '/{0}/{1}'
101+
path = path.format(
79102
str(postcode),
80103
str(house_number))
81104

82105
try:
83106
data = self.request(path)
84-
except Exception:
107+
except pyPostcodeException as e:
108+
logging.error(
109+
'Error looking up %s%s%s on %s: %d %s',
110+
postcode, house_number and ' ' or '', house_number, self.url,
111+
e.id, e.message)
112+
data = None
113+
except Exception as e:
114+
logging.exception(e)
85115
data = None
86116

87117
if data is not None:
@@ -93,107 +123,66 @@ def getaddress(self, postcode, house_number=None):
93123
class Resource(object):
94124

95125
def __init__(self, data):
96-
self._street = None
97-
self._house_number = None
98-
self._postcode = None
99-
self._town = None
100-
self._municipality = None
101-
self._province = None
102-
self._latitude = None
103-
self._longitude = None
104-
self._x = None
105-
self._y = None
106-
107-
if data is not None:
108-
self.setdata(data)
109-
110-
def setdata(self, data):
111126
self._data = data
112-
data_keys = self._data.keys()
113-
for key in data_keys:
114-
if hasattr(self, key):
115-
setattr(self, key, self._data[key])
116127

117128
@property
118129
def street(self):
119-
return self._street
120-
121-
@street.setter
122-
def street(self, value):
123-
self._street = value
130+
return self._data['street']
124131

125132
@property
126133
def house_number(self):
127134
'''
128135
House number can be empty when postcode search
129136
is used without house number
130137
'''
131-
return self._house_number
132-
133-
@house_number.setter
134-
def house_number(self, value):
135-
self._house_number = value
138+
return self._data.get('number', self._data.get('house_number'))
136139

137140
@property
138141
def postcode(self):
139-
return self._postcode
140-
141-
@postcode.setter
142-
def postcode(self, value):
143-
self._postcode = value
142+
return self._data.get('postcode')
144143

145144
@property
146145
def town(self):
147-
return self._town
148-
149-
@town.setter
150-
def town(self, value):
151-
self._town = value
146+
return self._data.get('city', {}).get('label', self._data.get('town'))
152147

153148
@property
154149
def municipality(self):
155-
return self._municipality
156-
157-
@municipality.setter
158-
def municipality(self, value):
159-
self._municipality = value
150+
result = self._data.get('municipality', {})
151+
if isinstance(result, dict):
152+
result = result.get('label')
153+
return result
160154

161155
@property
162156
def province(self):
163-
return self._province
157+
result = self._data.get('province', {})
158+
if isinstance(result, dict):
159+
result = result.get('label')
160+
return result
164161

165-
@province.setter
166-
def province(self, value):
167-
self._province = value
162+
def _get_geo_coordinates(self, geo_type):
163+
return self._data.get('geo', {}).get('center', {}).get(geo_type)\
164+
.get('coordinates', [None, None])
168165

169166
@property
170167
def latitude(self):
171-
return self._latitude
172-
173-
@latitude.setter
174-
def latitude(self, value):
175-
self._latitude = value
168+
if self._data.get('latitude'):
169+
return self._data.get('latitude')
170+
return self._get_geo_coordinates('wgs84')[0]
176171

177172
@property
178173
def longitude(self):
179-
return self._longitude
180-
181-
@longitude.setter
182-
def longitude(self, value):
183-
self._longitude = value
174+
if self._data.get('longitude'):
175+
return self._data.get('longitude')
176+
return self._get_geo_coordinates('wgs84')[1]
184177

185178
@property
186179
def x(self):
187-
return self._x
188-
189-
@x.setter
190-
def x(self, value):
191-
self._x = value
180+
if self._data.get('x'):
181+
return self._data.get('x')
182+
return self._get_geo_coordinates('rd')[0]
192183

193184
@property
194185
def y(self):
195-
return self._y
196-
197-
@y.setter
198-
def y(self, value):
199-
self._y = value
186+
if self._data.get('y'):
187+
return self._data.get('y')
188+
return self._get_geo_coordinates('rd')[1]

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
setup(
33
name = 'pyPostcode',
44
packages = ['pyPostcode'],
5-
version = '0.1',
5+
version = '0.2',
66
description = 'Request information about Dutch addresses from the PostcodeApi.nu API',
77
author = 'Stefan Jansen',
88
author_email = 'stefan@steffex.net',

0 commit comments

Comments
 (0)