Look up UK postcodes data from http://postcodes.io/.
Switch branches/tags
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.



This gem uses data gathered from the API at http://postcodes.io

It is an alternative to James Ruston's postcodes_io. postcodes_io works well on successful lookups, but does not provide information on why a lookup has failed. As I could not see an easy way of extending postcodes_io to provide this information without breaking previous implementations, the best option seemed to be to write an alternative.


Add this line to your application's Gemfile:

gem 'uk_postcodes_io'

And then execute:

$ bundle

Or install it yourself as:

$ gem install uk_postcodes_io


To look up a postcode:

lookup = UkPostcodesIo.lookup 'SW1A 2AA'

lookup.postcode == 'SW1A 2AA'
lookup.success? == true # depending on success of lookup

The data returned from the postcode.io API is presented as an object at lookup.data if the lookup is successful. For example, for the postcode of 10 Downing St ('SW1A 2AA'):

lookup.data.longitude == -0.127695242183412
lookup.data.latitude == 51.5035398826274

See the postcode.io documentation for a list of attributes available.

Multiple postcodes

Postcodes can be passed to UkPostcodesIo.multi_lookup as a list or an array:

lookup = UkPostcodesIo.multi_lookup 'SW1A 2AA', 'NW1 7JS'
lookup = UkPostcodesIo.multi_lookup ['SW1A 2AA', 'NW1 7JS']

UkPostcodesIo.multi_lookup, returns the data in a hash where the keys are the postcodes passed in, and the values are the matching data object. So:

lookup.data['SW1A 2AA'].longitude == -0.127695242183412
lookup.data['SW1A 2AA'].latitude == 51.5035398826274

However, note that if a postcode is not found, the request will be successful, but the value matching the problem postcode will be nil. So:

lookup.success? == true
lookup['NW1 7JS'] == nil


If the lookup fails:

lookup = UkPostcodesIo.lookup 'invalid'
lookup.success? == false
lookup.data == nil
lookup.error == 'Invalid postcode'

no_longer_valid_postcode = 'NW1 7JS'
lookup = UkPostcodesIo.lookup no_longer_valid_postcode
lookup.success? == false
lookup.data == nil
lookup.error == 'Postcode not found'


After checking out the repo, run bin/setup to install dependencies. Then, run rake test to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.


Bug reports and pull requests are welcome on GitHub at https://github.com/msventurelabs/uk_postcodes_io.


The gem is available as open source under the terms of the MIT License.