Documentation

Overview

Postcodes.io is a free Postcode lookup API and geocoder for the UK

Endpoint

All services can be accessed from the following HTTP[S] endpoint

https://api.postcodes.io

The API accepts GET and POST requests. POST methods use content type application/json

Responses

JSON(P) only. CORS is enabled.

Each response comes with an appropriate HTTP Status code (except for JSONP requests). These include 200 for success, 400 for bad request, 404 for not found and 500 for server error. The HTTP Status code is also included in the response body.

Authentication

Postcodes.io does not require any authentication.

Error Handling

To check for errors, examine the HTTP response code. 200 response indicates success while any other code will provide important information about why an error occured.

Alternatively, you can examine status code in the 'status' property in the result body.

All JSONP requests return 200 responses because of silent errors. When using JSONP, be sure to use the latter method to check for errors.

JSONP

JSONP requests are supported. Simply appended the URI with a callback name. E.g.

https://api.postcodes.io/postcodes/GU50BD?callback=foo

Versioning

The API currently does not use any form of versioning. Any changes to the API will be backwards-compatible, this includes: adding new properties to responses, adding new endpoints, adding new optional request parameters and changing the order of properties.

If we make backwards-incompatible changes in the future, this will be released under a versioned endpoint.

Available Data Fields

Postcode Data (Ordnance Survey Postcode Directory Dataset)

Data returned by the /postcodes and /outcodes API

FieldDescription
postcode Postcode. All current (‘live’) postcodes within the United Kingdom, the Channel Islands and the Isle of Man, received monthly from Royal Mail. 2, 3 or 4-character outward code, single space and 3-character inward code.
quality Positional Quality. Shows the status of the assigned grid reference.
  • 1 = within the building of the matched address closest to the postcode mean
  • 2 = as for status value 1, except by visual inspection of Landline maps (Scotland only)
  • 3 = approximate to within 50m
  • 4 = postcode unit mean (mean of matched addresses with the same postcode, but not snapped to a building)
  • 5 = imputed by ONS, by reference to surrounding postcode grid references
  • 6 = postcode sector mean, (mainly | PO Boxes)
  • 8 = postcode terminated prior to Gridlink® initiative, last known ONS postcode grid reference1
  • 9 = no grid reference available
eastings Eastings. The Ordnance Survey postcode grid reference Easting to 1 metre resolution; blank for postcodes in the Channel Islands and the Isle of Man. Grid references for postcodes in Northern Ireland relate to the Irish Grid system.
northings Northings. The Ordnance Survey postcode grid reference Northing to 1 metre resolution; blank for postcodes in the Channel Islands and the Isle of Man. Grid references for postcodes in Northern Ireland relate to the Irish Grid system.
country Country. The country (i.e. one of the four constituent countries of the United Kingdom or the Channel Islands or the Isle of Man) to which each postcode is assigned.
nhs_ha Strategic Health Authority. The health area code for the postcode.
admin_county County. The current county to which the postcode has been assigned.
admin_district District.The current district/unitary authority to which the postcode has been assigned.
admin_ward Ward. The current administrative/electoral area to which the postcode has been assigned.
longitudeLongitude. The WGS84 longitude given the Postcode's national grid reference
latitudeLatitude. The WGS84 latitude given the Postcode's national grid reference
parliamentary_constituency Westminster Parliamentary Constituency. The Westminster Parliamentary Constituency code for each postcode.
european_electoral_regionEuropean Electoral Region (EER). The European Electoral Region code for each postcode.
primary_care_trustPrimary Care Trust (PCT). The code for the Primary Care areas in England, LHBs in Wales, CHPs in Scotland, LCG in Northern Ireland and PHD in the Isle of Man; there are no equivalent areas in the Channel Islands. Care Trust/ Care Trust Plus (CT)/ local health board (LHB)/ community health partnership (CHP)/ local commissioning group (LCG)/ primary healthcare directorate (PHD).
regionRegion (formerly GOR). The Region code for each postcode. The nine GORs were abolished on 1 April 2011 and are now known as ‘Regions’. They were the primary statistical subdivisions of England and also the areas in which the Government Offices for the Regions fulfilled their role. Each GOR covered a number of local authorities.
parishParish (England)/ community (Wales).The smallest type of administrative area in England is the parish (also known as 'civil parish'); the equivalent units in Wales are communities.
lsoa2011Census lower layer super output area (LSOA). The 2011 Census lower layer SOA code for England and Wales, SOA code for Northern Ireland and data zone code for Scotland.
msoa2011 Census middle layer super output area (MSOA). The 2011 Census middle layer SOA (MSOA) code for England and Wales and intermediate zone for Scotland.
ccgClinical Commissioning Group. Clinical commissioning groups (CCGs) are NHS organisations set up by the Health and Social Care Act 2012 to organise the delivery of NHS services in England.
nuts Nomenclature of Units for Territorial Statistics (NUTS) / Local Administrative Units (LAU) areas. The LAU2 code for each postcode. NUTS is a hierarchical classification of spatial units that provides a breakdown of the European Union’s territory for producing regional statistics which are comparable across the Union. The NUTS area classification in the United Kingdom comprises current national administrative and electoral areas, except in Scotland where some NUTS areas comprise whole and/or part Local Enterprise Regions. NUTS levels 1-3 are frozen for a minimum of three years and NUTS levels 4 and 5 are now local Administrative Units (LAU) levels 1 and 2 respectively.
codes Returns an ID or Code associated with the postcode. Typically these are a 9 character code known as an ONS Code or GSS Code. This is currently only available for districts, parishes, counties, CCGs, NUTS and wards.

Places Data (Ordnance Survey Open Names Dataset)

Data returned by the /places API

FieldDescription
code code. A unique identifier that enables records to be identified easily. The identifier will be persistent for all LocalTypes except Section of Named Road and Section of Numbered Road.
eastings Eastings. The Ordnance Survey postcode grid reference Easting to 1 metre resolution; blank for postcodes in the Channel Islands and the Isle of Man.
northings Northings. The Ordnance Survey postcode grid reference Northing to 1 metre resolution; blank for postcodes in the Channel Islands and the Isle of Man.
[max|min]_northings, [max|min]_eastings Maximum & Minimum, Northings & Eastings. Bounding box or Minimum Bounding Rectangle (MBR) for roads and settlements. For Settlements and Sections of Named and Numbered Roads, the MBR gives a representation of the extent of these features and is not snapped to the real world extent.
country Country. The country (i.e. one of the four constituent countries of the United Kingdom or the Channel Islands or the Isle of Man) to which each place is assigned.
longitudeLongitude. The WGS84 longitude given the Place's national grid reference
latitudeLatitude. The WGS84 latitude given the Place's national grid reference
local_typeLocal Type. The Ordnance Survey classification for the named place being represented by the specific feature. E.g. City, Town, Village, Hamlet, Other Settlement, Suburban Area
outcodeOutcode. The postcode district, for example, SO15
name_1Name. The proper noun that applies to the real world entity. Names that are prefixed by the definite article are not formatted for alphabetical sorting, that is, ‘The Pennines’ not ‘Pennines, The’.
name_1_langLanguage of Name. The language type is only set where more than one name exists E.g. cym (Welsh), eng (English), gla (Scottish Gaelic)
name_2Name (in case of multiple languages). The proper noun that applies to the real world entity. Names that are prefixed by the definite article are not formatted for alphabetical sorting, that is, ‘The Pennines’ not ‘Pennines, The’.
name_2_langLanguage of Name. The language type is only set where more than one name exists E.g. cym (Welsh), eng (English), gla (Scottish Gaelic)
county_unitaryAdministrative Area. The name of the County (non-metropolitan or Metropolitan), Unitary Authority or Greater London Authority administrative area that the point geometry for feature is within or nearest to.
county_unitary_typeAdministrative Area Type. Classifies the type of administrative unit.
district_boroughDistrict or Borough. The name of the District, Metropolitan District or London Borough administrative unit that the point geometry for the feature is within.
district_borough_typeBorough Type. Classifies the type of administrative unit.
regionRegion. The name of the European Region (was Government O ice Region) that the point geometry for the feature is within or nearest to.

Methods

The following is a list of available API methods

Postcode Lookup

Lookup a postcode. Returns all available data if found. Returns 404 if postcode does not exist.

https://api.postcodes.io/postcodes/:postcode

Bulk Postcode Lookup

Accepts a JSON object containing an array of postcodes. Returns a list of matching postcodes and respective available data.

Accepts up to 100 postcodes.

POST
https://api.postcodes.io/postcodes

Post Data

This method requires a JSON object containing an array of postcodes to be posted. E.g.

{
  "postcodes" : ["PR3 0SG", "M45 6GN", "EX165BL"]
}

Reverse Geocoding

Returns nearest postcodes for a given longitude and latitude.

GET
https://api.postcodes.io/postcodes?lon=:longitude&lat=:latitude

Optional Query Parameters

limit= (not required) Limits number of postcodes matches to return. Defaults to 10. Needs to be less than 100.

radius= (not required) Limits number of postcodes matches to return. Defaults to 100m. Needs to be less than 2,000m.

wideSearch= (not required) Search up to 20km radius, but subject to a maximum of 10 results. Since lookups over a wide area can be very expensive, we've created this method to allow you choose to make the trade off between search radius and number of results. Defaults to false. When enabled, radius and limits over 10 are ignored.

Legacy

Note that the old style of reverse geocoding (including optional headers above) will still be supported. Namely,

GET
https://api.postcodes.io/postcodes/lon/:longitude/lat/:latitude

Bulk Reverse Geocoding

Bulk translates geolocations into Postcodes. Accepts up to 100 geolocations.

POST
https://api.postcodes.io/postcodes

Post Data

This method requires a JSON object containing an array of geolocation objects to be POSTed. Each geolocation object accepts an optional radius (meters) and limit argument. Both default to 100m and 10 respectively. It also accepts a wideSearch argument. E.g.

{
  "geolocations" : [{
  	"longitude" : -3.15807731271522,
  	"latitude" : 51.4799900627036
  },{
		"longitude" : -1.12935802905177,
  	"latitude" : 50.7186356978817,
  	"limit" : 100,
  	"radius" : 500
  }]
}

Postcode Query

Submit a postcode query and receive a complete list of postcode matches and all associated postcode data.

GET
https://api.postcodes.io/postcodes?q=[query]

Optional Query Parameters

query= (not required) aliases to q=

limit= (not required) Limits number of postcodes matches to return. Defaults to 10. Needs to be less than 100.

Postcode Validation

Convenience method to validate a postcode. Returns true or false (meaning valid or invalid respectively)

GET
https://api.postcodes.io/postcodes/:postcode/validate

Nearest Postcode

Returns nearest postcodes for a given postcode.

GET
https://api.postcodes.io/postcodes/:postcode/nearest

Optional Query Parameters

limit= (not required) Limits number of postcodes matches to return. Defaults to 10. Needs to be less than 100.

radius= (not required) Limits number of postcodes matches to return. Defaults to 100m. Needs to be less than 2,000m.

Postcode Autocomplete

Convenience method to return an list of matching postcodes.

GET
https://api.postcodes.io/postcodes/:postcode/autocomplete

Optional Query Parameters

limit= (not required) Limits number of postcodes matches to return. Defaults to 10. Needs to be less than 100.

Random Postcode

Returns a random postcode and all available data for that postcode.

GET
https://api.postcodes.io/random/postcodes

Optional Query Parameters

outcode= (not required) Filters random postcodes by outcode. Returns null if invalid outcode.

Outward Code Lookup

Geolocation data for the centroid of the outward code specified. The outward code represents the first half of any postcode (separated by a space).

GET
https://api.postcodes.io/outcodes/:outcode

Outcode Reverse Geocoding

Returns nearest outcodes for a given longitude and latitude.

GET
https://api.postcodes.io/outcodes?lon=:longitude&lat=:latitude

Optional Query Parameters

limit= (not required) Limits number of postcodes matches to return. Defaults to 10. Needs to be less than 100.

radius= (not required) Limits number of postcodes matches to return. Defaults to 5,000m. Needs to be less than 25,000m.

Nearest Outcode

Returns nearest outcodes for a given outcode.

GET
https://api.postcodes.io/outcodes/:outcode/nearest

Optional Query Parameters

limit= (not required) Limits number of postcodes matches to return. Defaults to 10. Needs to be less than 100.

radius= (not required) Limits number of postcodes matches to return. Defaults to 5,000m. Needs to be less than 25,000m.

Place Lookup

Lookup a place by code. Returns all available data if found. Returns 404 if place does not exist.

https://api.postcodes.io/places/:code

Place Query

Submit a place query and receive a complete list of places matches and associated data.

GET
https://api.postcodes.io/places?q=[query]

Optional Query Parameters

query= (not required) aliases to q=

limit= (not required) Limits number of places matches to return. Defaults to 10. Needs to be less than 100.

Random Place

Returns a random place and all associated data

GET
https://api.postcodes.io/random/places

Install Notes

There may be occasions where you want to host postcodes.io yourself. We've laid out instructions below on how to do this.

Installing Postcodes.io is matter of cloning the source. For example,

$ git clone https://github.com/ideal-postcodes/postcodes.io.git

We currently provide 3 methods to import the necessaru datasets

  1. The easiest is to use our install script. This will require postgres superuser privileges to create and provision your database. It will then download the database and import the data from a pg_dump (hosted and created by us).
  2. You can download the pg_dump and attempt to import the database yourself with psql or pg_restore.
  3. Lastly, you can retrieve the raw CSV data from the ONS and import it with our import script.

Requirements

Data Download

Data is sourced and can be downloaded from the Office for National Statistics Data Portal. The dataset is often not easy to find. The simplest way is to search for "Postcode Directory".

Alternatively you can download a pg_dump of the postcode database which is hosted by us. This is the same dump which is used by the install script. The link to the latest dump can be found in our repository.

Install Script

Currently the install process targets *nix systems. We've provisioned and tested on OS X Mavericks & Ubuntu 14.04. Please let us know if you have issues on other operating systems.

Postcodes.io is packaged with a script to provision postgres and download a dump (pg_dump) of the ONS Postcode Directory (hosted by us). The script will do the following,

  • Prompt you for your postgres superuser credentials (most of the setup steps require this level of privilege)
  • Create a new user "postcodesio"
  • Create a new database "postcodesiodb" owned by "postcodesio"
  • Create the necessary extensions on "postcodesiodb"
  • Download, unzip and stream the Postcode directory into Postgres

To run,

$ npm run setup

Manual Installation from our pg_dump

To setup the database from our pg_dump simply download, gunzip and use either psql or pg_restore to import the data into Postgresql.

For example,

$ cat postcodeiodb.sql | psql postcodesiodb

Manual Installation

The install scripts can be linked to your shell (or can be found in the bin/ directory). To link, navigate to postcodes.io/ and run $ npm link

ONS Postcode Directory

Download the latest Office for National Statistic's "Postcode Lookup Dataset". Unzip the data locally. Run the import script $ onsImport passing the path to the CSV data.

$ onsImport /path/to/data/ONSPD/Data/data.csv

OS Open Names

Download the latest Ordnance Survey Open Names dataset. Unzip the data locally. Run the import script $ osPlaceImport passing the path that contains the CSV data files.

$ osPlaceImport /path/to/data/opname_csv_gb/Data/

Data Updates

If you wish to manually update your data or data schema, we provide a script which will do this for you with minimal downtime (currently ~10-20 seconds to generate smaller relations).

ONS Postcode Directory

Download the latest Office for National Statistic's "Postcode Lookup Dataset" and run the import script $ onsUpdate passing the path to the CSV data.

$ onsUpdate /path/to/data/ONSPD/Data/data.csv

OS Open Names

Currently not implemented