Skip to main content

Postcode lookup

lookup returns the addresses at a postcode, or the API's closest matching postcodes when it is not found. It never raises for an unknown postcode.

lookup.rbruby
require "ideal_postcodes"

client = IdealPostcodes::Client.new(api_key: "ak_test")
lookup = client.lookup("BR8 7RE")

if lookup.found?
lookup.addresses.each do |address|
puts "#{address.line_1}, #{address.post_town}, #{address.postcode}"
end
else
puts "Did you mean: #{lookup.suggestions.join(', ')}"
end

Return value​

An IdealPostcodes::Client::PostcodeLookup.

ReaderContents
found?true when the postcode exists
addressesThe addresses on this page, as AddressListItem objects. [] when not found
suggestionsUp to five closest matching postcodes when not found, otherwise []
totalAddresses at the postcode across all pages. 0 when not found

An unfound postcode costs no lookup. Other errors, such as an invalid key or an empty balance, still raise IdealPostcodes::ApiError. See error handling.

Raw response​

postcodes returns the full PostcodeResponse, with page, limit and total, and raises ApiError with code 4040 when the postcode is not found. Use it when you page through a large postcode or want the raw response.

retrieve.rbruby
response = client.postcodes("BR8 7RE", page: 0)

puts "#{response.total} addresses, #{response.result.size} on this page"

Pagination​

A small number of postcodes return more than 100 premises. The API returns 100 addresses per page, so pass page: until you have total addresses.

pages.rbruby
addresses = []
page = 0

loop do
response = client.postcodes("CV4 7AL", page: page)
addresses.concat(response.result)
page += 1
break if addresses.size >= response.total
end

Field filter​

Pass filter: with the fields you need, as a comma separated string or an array. Fields left out of the response read as nil.

filter.rbruby
lookup = client.lookup("BR8 7RE", filter: %w[line_1 line_2 post_town postcode])

lookup takes every keyword postcodes does. Each one is on the postcodes reference page.