Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ This API allows you to search for Dutch addresses using zipcodes.

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

This library supports both the v1 and the v2 api, defaulting to v1 for now.


##Installation

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

postcodeapi = Api('{YOUR_API_KEY}') # Set your own API-key
# if you want to use the v2 api, say
postcodeapi = Api('{YOUR_API_KEY}', (2, 0, 0))
result = postcodeapi.getaddress('1011AC', 154) # use address search
print result.street, result.house_number, result.town
```
Expand Down
12 changes: 11 additions & 1 deletion example.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,14 @@
postcodeapi = Api('{YOUR_API_KEY}')
result_street = postcodeapi.getaddress('1011AC') # use p6 search
result_address = postcodeapi.getaddress('1011AC', 154) # use address search
print result_street._data, result_address._data
for result in [result_street, result_address]:
print result.street
print result.house_number
print result.postcode
print result.town
print result.municipality
print result.province
print result.latitude
print result.longitude
print result.x
print result.y
143 changes: 66 additions & 77 deletions pyPostcode/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

import httplib
import json
import logging


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

class Api(object):

def __init__(self, api_key):
def __init__(self, api_key, api_version=(1, 0, 0)):
if api_key is None or api_key is '':
raise pyPostcodeException(
0, "Please request an api key on http://postcodeapi.nu")

self.api_key = api_key
self.url = 'api.postcodeapi.nu'
self.api_version = api_version
if api_version >= (2, 0, 0):
self.url = 'postcode-api.apiwise.nl'
else:
self.url = 'api.postcodeapi.nu'

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

headers = {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"Accept": "application/json",
"Accept-Language": "en",
"Api-Key": self.api_key}

conn = httplib.HTTPConnection(self.url)
# this is the v1 api
"Api-Key": self.api_key,
# this is the v2 api
"X-Api-Key": self.api_key,
}

if self.api_version >= (2, 0, 0):
conn = httplib.HTTPSConnection(self.url)
else:
conn = httplib.HTTPConnection(self.url)
'''Only GET is supported by the API at this time'''
conn.request('GET', path, None, headers)

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

jsondata = json.loads(resultdata)
data = jsondata['resource']

if self.api_version >= (2, 0, 0):
data = jsondata.get('_embedded', {}).get('addresses', [])
if data:
data = data[0]
else:
data = None
else:
data = jsondata['resource']

return data

def getaddress(self, postcode, house_number=None):
if house_number is None:
house_number = ''

path = '/{0}/{1}'.format(
if self.api_version >= (2, 0, 0):
path = '/v2/addresses/?postcode={0}&number={1}'
else:
path = '/{0}/{1}'
path = path.format(
str(postcode),
str(house_number))

try:
data = self.request(path)
except Exception:
except pyPostcodeException as e:
logging.error(
'Error looking up %s%s%s on %s: %d %s',
postcode, house_number and ' ' or '', house_number, self.url,
e.id, e.message)
data = None
except Exception as e:
logging.exception(e)
data = None

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

def __init__(self, data):
self._street = None
self._house_number = None
self._postcode = None
self._town = None
self._municipality = None
self._province = None
self._latitude = None
self._longitude = None
self._x = None
self._y = None

if data is not None:
self.setdata(data)

def setdata(self, data):
self._data = data
data_keys = self._data.keys()
for key in data_keys:
if hasattr(self, key):
setattr(self, key, self._data[key])

@property
def street(self):
return self._street

@street.setter
def street(self, value):
self._street = value
return self._data['street']

@property
def house_number(self):
'''
House number can be empty when postcode search
is used without house number
'''
return self._house_number

@house_number.setter
def house_number(self, value):
self._house_number = value
return self._data.get('number', self._data.get('house_number'))

@property
def postcode(self):
return self._postcode

@postcode.setter
def postcode(self, value):
self._postcode = value
return self._data.get('postcode')

@property
def town(self):
return self._town

@town.setter
def town(self, value):
self._town = value
return self._data.get('city', {}).get('label', self._data.get('town'))

@property
def municipality(self):
return self._municipality

@municipality.setter
def municipality(self, value):
self._municipality = value
result = self._data.get('municipality', {})
if isinstance(result, dict):
result = result.get('label')
return result

@property
def province(self):
return self._province
result = self._data.get('province', {})
if isinstance(result, dict):
result = result.get('label')
return result

@province.setter
def province(self, value):
self._province = value
def _get_geo_coordinates(self, geo_type):
return self._data.get('geo', {}).get('center', {}).get(geo_type)\
.get('coordinates', [None, None])

@property
def latitude(self):
return self._latitude

@latitude.setter
def latitude(self, value):
self._latitude = value
if self._data.get('latitude'):
return self._data.get('latitude')
return self._get_geo_coordinates('wgs84')[0]

@property
def longitude(self):
return self._longitude

@longitude.setter
def longitude(self, value):
self._longitude = value
if self._data.get('longitude'):
return self._data.get('longitude')
return self._get_geo_coordinates('wgs84')[1]

@property
def x(self):
return self._x

@x.setter
def x(self, value):
self._x = value
if self._data.get('x'):
return self._data.get('x')
return self._get_geo_coordinates('rd')[0]

@property
def y(self):
return self._y

@y.setter
def y(self, value):
self._y = value
if self._data.get('y'):
return self._data.get('y')
return self._get_geo_coordinates('rd')[1]
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
setup(
name = 'pyPostcode',
packages = ['pyPostcode'],
version = '0.1',
version = '0.2',
description = 'Request information about Dutch addresses from the PostcodeApi.nu API',
author = 'Stefan Jansen',
author_email = 'stefan@steffex.net',
Expand Down