Documentation

Introduction

Open Postcodes API provides accurate, up-to-date address level information for any UK postcode in JSON format. Data is proved at a highly competitive rate, starting at just 1p per lookup and additional functionality free of charge. To access these resources, free and paid, you must sign up for an API key.

This page documents the API resources with various different programming language examples and their respective plugins.

Getting Started

Create an API Key

First sign up for an Open Postcodes account. Signing up is completely free and requires no payment information to get started. Once signed in, you will be able to create a key from your account area. You will be asked if the key is for a public or private application, you can find more information on the differences here.

Implementation & Testing

Once created the key will be instantly active on our systems. You must provide the key in every API request, this is done using the api_key parameter, find out more information about authentication. We provide a number of test postcodes to ensure the correct implementation of our system, these postcodes do not count towards your lookups limits or purchased lookups, more information about testing.

Going Live

When you have tested your implementation you will be ready to take your key live. To do this sign in to your account and purchase lookup blocks for the specific key, upon successful payment lookups will be credited to your account instantly.

API Overview

API Endpoint

The API endpoint will never change, it can be hard coded into your system.

https://api.openpostcodes.com

Methods

The only accepted method on this API are GET requests, all other request types will return a Not Found (404) error. The API only accepts HTTPS connections any plain HTTP connections will be refused by the server.

Authentication

Every request sent requires a valid API key for authentication purposes. This is done by passing the api_key parameter in the query string with your unique key as the value, as shown in the example below.

https://api.openpostcodes.com/v1/postcodes/XA10XX?api_key=openpostcodes_demo

For more detailed information regarding authentication.

Responses

All request responses are returned with the appropriate HTTP status code as well as a custom code to provide more information to developers, more about response codes. All response data is returned in JSON format, if you wish to receive response data in a different format please contact support.

Versioning

The API uses a versioning system, the version can be specified in every request sent, bold in the example below.

https://api.openpostcodes.com/v1

Providing a version number is not required, if you don't provide a version we will assume you want to use the latest version of the API, more information on versioning.

Error Handling

Successful requests are returned with a HTTP status code of 200 and a response code of 2000, response codes are found in the JSON response data under the code parameter. If an error has occurred the HTTP status code returned will be something other than 200, in this situation you can match the error code to an error message to debug the problem. More information about error codes.

Testing

We provide test data for every scenario which has no impact on your API key balance, more information about testing.

JSONP

JSONP requests are fully supported by our system. To use a JSONP request add the callback parameter, to your request query, with the name of the function you want to invoke as shown below.

https://api.openpostcodes.com/v1/postcodes/XA10XX?api_key=openpostcodes_demo&callback=foobar

The response result will then be wrapped in the specified callback function as shown below.

foobar({"result":[
    {
        "postcode": "XA1 0XX",
        "line_1": "The Pavilion",
        "line_2": "Oaks Avenue",
        "line_3": "",
        "post_town": "LONDON",
        "organisation_name": "",
        "building_name": "The Pavilion",
        /* Truncated ... */
    }],
    "code": 2000,
    "message": "Success"
});

Authentication

API Keys

Every request requires the presents of a valid API key for authentication by passing your key using the api_key parameter, as show below.

https://api.openpostcodes.com/v1/postcodes/XA10XX?api_key=openpostcodes_demo

If you send a request without a API present you will receive a HTTP 401 Unauthorised error and you request will not be fulfilled. Authentication is also required when using the free resources provided this is to prevent abuse.

Access Restrictions

We provide the ability to limit the usage and access to the API via your key. These access restrictions are set on a per key basis, allowing you to opt high or low usage restrictions dependant on your application.

Daily Lookup Limit

Limiting the total amount of daily lookups means you will only use maximum of this value from your key balance on a daily basis. The daily count is reset, back to zero, at 00:00 GMT every day. Please keep in mind that this limit could technically be consumed by one individual, in order to limit lookups on an individual basis look at the Daily Individual Lookup Limit below.

Daily Individual Lookup Limit

This provides a limit on the total number of lookups an individual can perform a day on a given API key. An individual is defined as an IP address therefore preventing abuse from a single IP. The limit is reset, back to zero, at 00:00 GMT every day. This provides additional protection against abuse especially when using the client-side jQuery postcode lookup plugin.

Allowed URLs

When using a client-side scripting language, such as Javascript, to send and receive requests it is highly recommended that you use Allowed URL lists to prevent non-permitted websites or applications using your lookups.

To add an Allowed URL, go to your account dashboard, select a key and open the Restrictions tab. When the first URL is added only that URL will have access to the API using the specified key. You can add URLs on a domain or per page basis, for example

openpostcodes.com
openpostcodes.com/checkout
openpostcodes.com/account/sign-up

Response Codes

The API provides 2 status indicators in order for you to determine the correct status of each request.

The primary indicator is a HTTP status code, which is present in every HTTP request, this code complies with HTTP 1.1 specifications. For example 2xx codes indicate a successful request, 4xx codes indicate a client request error and 5xx codes indicate a server error. 2xx, 4xx and 5xx are the only HTTP codes used by the Open Postcodes API.

The secondary indicator is a custom code found in the response data, under the code parameter, each custom indicator code is an extension of its comparable HTTP code. This code is linked to a specific reason the request has failed, this provides greater granularity when debugging.

Listed below are an index of error codes and the errors associated with them.

Success (200)

Standard response for a successful request

2000
Success Request was completed successfully

Unauthorised (401)

Authentication credentials are invalid or have not been provided

4010
Invalid Key Key provided was not valid
4011
Referer Excluded HTTP referer provided is not in the keys allowed URLs list, more information about allowed URLs in access restrictions

Lookup Failed (402)

Your request is valid, however it could not be completed

4020
Lookups Exhausted Your key was out of lookups, buy more in your account area
4021
Limit Reached One of your specified key lookup limits has been reached today. Daily lookup limits are reset at 00:00 GMT. You can increase or disable your limit on a particular key in your account area

Resource Not Found (404)

The requested resource could not be found

4040
Postcode Not Found The requested postcode does not exist

Unprocessable Entity (422)

There was an error in your query parameters

4220
Invalid Input An input parameter has an invalid value

Internal Server Error (5xx)

5xx are errors server errors, which are our responsibility. Any 5xx errors are logged and reported to us so we can further investigate what went wrong when detailing with your request. If you require an immediate resolution to the issue please contact support.

JSONP Requests

Due to JSONP requests frequently being neglected in web browsers when a status code other than 200 is issued, meaning there is no information in which to process errors. In order to combat this the Open Postcodes API will respond to all JSONP requests with a HTTP status code of 200, even when an error has occurred, therefore JSONP requests must use the response code provided in the response body rather than rely on any HTTP codes.

Versioning

The Open Postcodes API uses a versioning system to ensure backwards compatibility, with older implementations, and newer functionality for current implementations. Versioning is handled using a version segment in the request URL, as shown below.

https://api.openpostcodes.com/v1

In this case v1 which equates Version 1.

This version identifier will only be updated in major version changes such as "v1", "v2", "v3" and so on, this is because any minor changes or updates will not affect the compatibility within major versions. Failure to provide the version identifier will result in the API using latest version syntax, to ensure backwards compatibility always specify the version.

To keep up to date with the latest API changes you can subscribe to our Alterations emails in your account area under the "Edit Account" tab.

Resources

Below are fully documented resources which can be accessed via the API. Some resources will incur charges to your account unless specified as free.

Postcode

The postcode lookup method returns all address information relating to an individual United Kingdom postcode.

Postcode Object

postcode
string    example: XA1 0XX Formatted postcode which is spaced and capitalised
postcode_inward
string    example: 0XX An Inward code is the second half of a postcode, it is always represented by 3 characters specifically 1 number succeeded by 2 letters. The number refers to the Postcode Sector and the last 2 letters define the Unit Postcode, which can identify one or more properties.
postcode_outward
string    example: XA1 A Outward code is the first half of a postcode, it is between 2 and 4 characters in length. This segment of the postcode contains the Area Code, at the start, and the Postcode District.
post_town
string    example: LONDON Post Town is a required element for successful postal delivery, therefore will always be present. For a limited number of addresses the only element of locality will be the Post Town.
dependant_locality
string    example: Wimbledon Dependant Locality is necessary if the same street name occurs more than once in a single Post Town in order to further define the geographic area.
double_dependant_locality
string    example: Wood Industrial Estate Double Dependent Locality is only populated when the Dependent Locality is populated and occurs more than once is the same locality.
thoroughfare
string    example: Oaks Avenue Thoroughfare can also be referred to as the road or street name. Generally each Thoroughfare will have a unique Postcode, however geographically longer Thoroughfares will span multiple postcodes.
dependant_thoroughfare
string    example: Ash Road Dependant Thoroughfare is used to further define the original Thoroughfare when there is more than a single instance in a Post Town.
building_number
string    example: 10 Building Number is used to find an individual premise on a Thoroughfare or Dependant Thoroughfare.
building_name
string    example: The Pavilion Building name of a commercial or residential premise.
sub_building_name
string    example: Flat 1 A Sub Building is used when a single premise is segmented into separate premises, for example commercial units or residential apartments.
po_box
string    example: 428 PO Box provides the PO Box identifier field, note that this field can contain both letters and numbers up to a length of 6 characters. PO Boxes are strictly only allocated to Large Users.
department_name
string    example: Accounts Dept Department Name is used to further define a department within an organisation when an Organisation Name is present.
organisation_name
string    example: Lumberjacks Limited Organisation Name registered at this address.
udprn
integer    example: 123456 UDPRN is an abbreviation for Unique Delivery Point Reference Number. Very unlikely to be reissued when an address is no longer valid.
postcode_type
string    example: S Postcode Type relates to the type of user, it can only contain 2 different values "S" indicating a Small User or "L" indicating a Large User. Large Users are identified by an accompanying PO Box or because the address receives a large amount of mail.
su_organisation_indicator
string    example: Y Small User Organisation Indicator only has 2 valid values, "Y" meaning a Small User Organisation is present at this address, or its left blank meaning no there is no Small User Organisation Present at this address.
delivery_point_suffix
string    example: 2U Delivery Point Suffix is a 2 character value, the first a number and the second a letter. When the Delivery Point Suffix is added to the Postcode it forms a uniquely identified Delivery Point. When a Large User exists on a Postcode the Delivery Point Suffix will always be 1A.
line_1
string    example: Flat 1 Line 1 of address. This address line is never empty. Usually consists of premise and Thoroughfare information for residential properties and the name of the Organisation for commercial premises.
line_2
string    example: The Pavilion Line 2 of address. This address line can be empty. Usually consists of Thoroughfare and Locality data.
line_3
string    example: Oaks Avenue Line 3 of address. This address line can be empty. Contains information to further define an individual premise.
longitude
decimal    example: -0.087480458807402 Longitude of the Postcode. Can contain a positive of negative decimal notation. Accurate at the altitude of the Postcode.
latitude
decimal    example: 51.426390555825 Latitude of the Postcode. Can contain a positive of negative decimal notation. Accurate at the altitude of the Postcode.
eastings
integer    example: 533062 Eastings reference using the Ordnance Survey National Grid reference system. Amount of Metres from origin.
northings
integer    example: 171444 Northings reference using the Ordnance Survey National Grid reference system. Amount of Metres from origin.

Postcode Lookup

The postcode lookup method returns all address information relating to an individual United Kingdom postcode.

Query URI

postcodes/:postcode GET

Query Parameters

api_key
required For authentication, found in your account area.

Example Request

https://api.openpostcodes.com/postcodes/XA10XX?api_key=openpostcodes_demo GET

Example Response

200{
    "result": [
        {
            "postcode": "XA1 0XX",
            "postcode_inward": "0XX",
            "postcode_outward": "XA1",
            "post_town": "LONDON",
            "dependant_locality": "",
            "double_dependant_locality": "",
            "thoroughfare": "Oaks Avenue",
            "dependant_thoroughfare": "",
            "building_number": "",
            "building_name": "The Pavilion",
            "sub_building_name": "",
            "po_box": "",
            "department_name": "",
            "organisation_name": "",
            "udprn": 22088057,
            "postcode_type": "S",
            "su_organisation_indicator": "",
            "delivery_point_suffix": "2U",
            "line_1": "The Pavilion",
            "line_2": "Oaks Avenue",
            "line_3": "",
            "longitude": -0.087480458807402,
            "latitude": 51.426390555825,
            "eastings": 533062,
            "northings": 171444
        },
        {
            "postcode": "XA1 0XX",
            "postcode_inward": "0XX",
            "postcode_outward": "XA1",
            "post_town": "LONDON",
            "dependant_locality": "",
            "double_dependant_locality": "",
            "thoroughfare": "Oaks Avenue",
            "dependant_thoroughfare": "",
            "building_number": "1",
            "building_name": "",
            "sub_building_name": "",
            "po_box": "",
            "department_name": "",
            "organisation_name": "",
            "udprn": 22088058,
            "postcode_type": "S",
            "su_organisation_indicator": "",
            "delivery_point_suffix": "1A",
            "line_1": "1 Oaks Avenue",
            "line_2": "",
            "line_3": "",
            "longitude": -0.087480458807402,
            "latitude": 51.426390555825,
            "eastings": 533062,
            "northings": 171444
        },
        {
            "postcode": "XA1 0XX",
            "postcode_inward": "0XX",
            "postcode_outward": "XA1",
            "post_town": "LONDON",
            "dependant_locality": "",
            "double_dependant_locality": "",
            "thoroughfare": "Oaks Avenue",
            "dependant_thoroughfare": "",
            "building_number": "2",
            "building_name": "",
            "sub_building_name": "",
            "po_box": "",
            "department_name": "",
            "organisation_name": "",
            "udprn": 22088059,
            "postcode_type": "S",
            "su_organisation_indicator": "",
            "delivery_point_suffix": "1Q",
            "line_1": "2 Oaks Avenue",
            "line_2": "",
            "line_3": "",
            "longitude": -0.087480458807402,
            "latitude": 51.426390555825,
            "eastings": 533062,
            "northings": 171444
        },
        {
            "postcode": "XA1 0XX",
            "postcode_inward": "0XX",
            "postcode_outward": "XA1",
            "post_town": "LONDON",
            "dependant_locality": "",
            "double_dependant_locality": "",
            "thoroughfare": "Oaks Avenue",
            "dependant_thoroughfare": "",
            "building_number": "3",
            "building_name": "",
            "sub_building_name": "",
            "po_box": "",
            "department_name": "",
            "organisation_name": "",
            "udprn": 22088060,
            "postcode_type": "S",
            "su_organisation_indicator": "",
            "delivery_point_suffix": "2D",
            "line_1": "3 Oaks Avenue",
            "line_2": "",
            "line_3": "",
            "longitude": -0.087480458807402,
            "latitude": 51.426390555825,
            "eastings": 533062,
            "northings": 171444
        },
        {
            "postcode": "XA1 0XX",
            "postcode_inward": "0XX",
            "postcode_outward": "XA1",
            "post_town": "LONDON",
            "dependant_locality": "",
            "double_dependant_locality": "",
            "thoroughfare": "Oaks Avenue",
            "dependant_thoroughfare": "",
            "building_number": "4",
            "building_name": "",
            "sub_building_name": "",
            "po_box": "",
            "department_name": "",
            "organisation_name": "",
            "udprn": 22088061,
            "postcode_type": "S",
            "su_organisation_indicator": "",
            "delivery_point_suffix": "2N",
            "line_1": "4 Oaks Avenue",
            "line_2": "",
            "line_3": "",
            "longitude": -0.087480458807402,
            "latitude": 51.426390555825,
            "eastings": 533062,
            "northings": 171444
        },
        {
            "postcode": "XA1 0XX",
            "postcode_inward": "0XX",
            "postcode_outward": "XA1",
            "post_town": "LONDON",
            "dependant_locality": "",
            "double_dependant_locality": "",
            "thoroughfare": "Oaks Avenue",
            "dependant_thoroughfare": "",
            "building_number": "5",
            "building_name": "",
            "sub_building_name": "",
            "po_box": "",
            "department_name": "",
            "organisation_name": "",
            "udprn": 22088062,
            "postcode_type": "S",
            "su_organisation_indicator": "",
            "delivery_point_suffix": "2P",
            "line_1": "5 Oaks Avenue",
            "line_2": "",
            "line_3": "",
            "longitude": -0.087480458807402,
            "latitude": 51.426390555825,
            "eastings": 533062,
            "northings": 171444
        },
        {
            "postcode": "XA1 0XX",
            "postcode_inward": "0XX",
            "postcode_outward": "XA1",
            "post_town": "LONDON",
            "dependant_locality": "",
            "double_dependant_locality": "",
            "thoroughfare": "Oaks Avenue",
            "dependant_thoroughfare": "",
            "building_number": "6",
            "building_name": "",
            "sub_building_name": "",
            "po_box": "",
            "department_name": "",
            "organisation_name": "",
            "udprn": 22088063,
            "postcode_type": "S",
            "su_organisation_indicator": "",
            "delivery_point_suffix": "2Q",
            "line_1": "6 Oaks Avenue",
            "line_2": "",
            "line_3": "",
            "longitude": -0.087480458807402,
            "latitude": 51.426390555825,
            "eastings": 533062,
            "northings": 171444
        },
        {
            "postcode": "XA1 0XX",
            "postcode_inward": "0XX",
            "postcode_outward": "XA1",
            "post_town": "LONDON",
            "dependant_locality": "",
            "double_dependant_locality": "",
            "thoroughfare": "Oaks Avenue",
            "dependant_thoroughfare": "",
            "building_number": "7",
            "building_name": "",
            "sub_building_name": "",
            "po_box": "",
            "department_name": "",
            "organisation_name": "Lumberjacks Limited",
            "udprn": 22088064,
            "postcode_type": "S",
            "su_organisation_indicator": "",
            "delivery_point_suffix": "2R",
            "line_1": "Lumberjacks Limited",
            "line_2": "7 Oaks Avenue",
            "line_3": "",
            "longitude": -0.087480458807402,
            "latitude": 51.426390555825,
            "eastings": 533062,
            "northings": 171444
        },
        {
            "postcode": "XA1 0XX",
            "postcode_inward": "0XX",
            "postcode_outward": "XA1",
            "post_town": "LONDON",
            "dependant_locality": "",
            "double_dependant_locality": "",
            "thoroughfare": "Oaks Avenue",
            "dependant_thoroughfare": "",
            "building_number": "8",
            "building_name": "",
            "sub_building_name": "",
            "po_box": "",
            "department_name": "",
            "organisation_name": "Flooring Company",
            "udprn": 22088065,
            "postcode_type": "S",
            "su_organisation_indicator": "",
            "delivery_point_suffix": "2S",
            "line_1": "Flooring Company",
            "line_2": "8 Oaks Avenue",
            "line_3": "",
            "longitude": -0.087480458807402,
            "latitude": 51.426390555825,
            "eastings": 533062,
            "northings": 171444
        },
        {
            "postcode": "XA1 0XX",
            "postcode_inward": "0XX",
            "postcode_outward": "XA1",
            "post_town": "LONDON",
            "dependant_locality": "",
            "double_dependant_locality": "",
            "thoroughfare": "Oaks Avenue",
            "dependant_thoroughfare": "",
            "building_number": "10",
            "building_name": "",
            "sub_building_name": "",
            "po_box": "",
            "department_name": "",
            "organisation_name": "",
            "udprn": 22088067,
            "postcode_type": "S",
            "su_organisation_indicator": "",
            "delivery_point_suffix": "1B",
            "line_1": "10 Oaks Avenue",
            "line_2": "",
            "line_3": "",
            "longitude": -0.087480458807402,
            "latitude": 51.426390555825,
            "eastings": 533062,
            "northings": 171444
        },
        {
            "postcode": "XA1 0XX",
            "postcode_inward": "0XX",
            "postcode_outward": "XA1",
            "post_town": "LONDON",
            "dependant_locality": "",
            "double_dependant_locality": "",
            "thoroughfare": "Oaks Avenue",
            "dependant_thoroughfare": "",
            "building_number": "11",
            "building_name": "",
            "sub_building_name": "",
            "po_box": "",
            "department_name": "",
            "organisation_name": "",
            "udprn": 22088068,
            "postcode_type": "S",
            "su_organisation_indicator": "",
            "delivery_point_suffix": "1D",
            "line_1": "11 Oaks Avenue",
            "line_2": "",
            "line_3": "",
            "longitude": -0.087480458807402,
            "latitude": 51.426390555825,
            "eastings": 533062,
            "northings": 171444
        },
        {
            "postcode": "XA1 0XX",
            "postcode_inward": "0XX",
            "postcode_outward": "XA1",
            "post_town": "LONDON",
            "dependant_locality": "",
            "double_dependant_locality": "",
            "thoroughfare": "Oaks Avenue",
            "dependant_thoroughfare": "",
            "building_number": "12",
            "building_name": "",
            "sub_building_name": "",
            "po_box": "",
            "department_name": "",
            "organisation_name": "",
            "udprn": 22088069,
            "postcode_type": "S",
            "su_organisation_indicator": "",
            "delivery_point_suffix": "1E",
            "line_1": "12 Oaks Avenue",
            "line_2": "",
            "line_3": "",
            "longitude": -0.087480458807402,
            "latitude": 51.426390555825,
            "eastings": 533062,
            "northings": 171444
        }
    ],
    "code": 2000,
    "message": "Successful"
}

Location

The location resource allows you to query a specific location, in the form of Longitude and Latitude coordinates, and return a list of postcodes within a provided radius.

Using the location resource is free and will not count towards your API key lookups.

Location Object

postcode
string    example: SE19 1QB Formatted postcode which is spaced and capitalised
eastings
integer    example: 533064 Eastings reference using the Ordnance Survey National Grid reference system. Amount of Metres from origin.
northings
integer    example: 171480 Northings reference using the Ordnance Survey National Grid reference system. Amount of Metres from origin.
longitude
decimal    example: -0.087438200521935 Longitude of the Postcode. Can contain a positive of negative decimal notation. Accurate at the altitude of the Postcode.
latitude
decimal    example: 51.426713602917 Latitude of the Postcode. Can contain a positive of negative decimal notation. Accurate at the altitude of the Postcode.
distance
decimal    example: 36.1 Distance in metres from the original Longitude and Latitude coordinates provided to the Postcode.

Location Request

Returns a list of postcodes which match provided geographical constraints.

Query URI

GET
postcodes

Query Parameters

api_key
required For authentication, found in your account area.
lonlat
required The Longitude and Latitude coordinates of the location you want to query. Lonlat is correctly formated with the Longitude and Latitude separated by a comma with no spaces, as show in the example.
radius
optional    default: 100    maximum: 1000 Set the radius, in metres, within the postcode must be from the specified coordinates to be returned as a result.
limit
optional    default: 100    maximum: 150 Maximum amount of postcodes which will be returned. If there are less which match the location criteria then only those results will be returned. If there are more than the defined limit then only the closest geographically will be returned.

Example Request

GET
https://api.openpostcodes.com/postcodes/?api_key=openpostcodes_demo&lonlat=-0.087480,51.426390&radius=200&limit=10

Example Response

200{
    "result": [
        {
            "postcode": "SE19 1QY",
            "eastings": 533062,
            "northings": 171444,
            "longitude": -0.087480458807402,
            "latitude": 51.426390555825,
            "distance": 0.07
        },
        {
            "postcode": "SE19 1QB",
            "eastings": 533064,
            "northings": 171480,
            "longitude": -0.087438200521935,
            "latitude": 51.426713602917,
            "distance": 36.1
        },
        {
            "postcode": "SE19 1QX",
            "eastings": 533128,
            "northings": 171497,
            "longitude": -0.086511813766508,
            "latitude": 51.426851356322,
            "distance": 84.48
        },
        {
            "postcode": "SE27 9RB",
            "eastings": 533064,
            "northings": 171533,
            "longitude": -0.087418312801163,
            "latitude": 51.427189890745,
            "distance": 89.05
        },
        {
            "postcode": "SE19 1JA",
            "eastings": 533030,
            "northings": 171351,
            "longitude": -0.087975344656453,
            "latitude": 51.425562311226,
            "distance": 98.23
        },
        {
            "postcode": "SE19 1RA",
            "eastings": 533168,
            "northings": 171440,
            "longitude": -0.085958214292916,
            "latitude": 51.426329732635,
            "distance": 105.72
        },
        {
            "postcode": "SE19 1QZ",
            "eastings": 532947,
            "northings": 171467,
            "longitude": -0.089124959868383,
            "latitude": 51.426624213761,
            "distance": 116.98
        },
        {
            "postcode": "SE19 1RB",
            "eastings": 533175,
            "northings": 171485,
            "longitude": -0.085840690188824,
            "latitude": 51.426732484104,
            "distance": 119.87
        },
        {
            "postcode": "SE27 9QY",
            "eastings": 533035,
            "northings": 171570,
            "longitude": -0.087821313326697,
            "latitude": 51.427529196431,
            "distance": 128.86
        },
        {
            "postcode": "SE19 1QW",
            "eastings": 533166,
            "northings": 171357,
            "longitude": -0.08601813121041,
            "latitude": 51.425584317977,
            "distance": 135.27
        }
    ],
    "code": 2000,
    "message": "Success"
}

Code Examples

We provide working examples of how to successfully interact with the API in the most common programming languages. There are also official libraries provided in some cases in order to aid the development process.

Java

The example below demonstrates how to perform a postcode lookup using the Java language without using any external or 3rd party libraries.

Java Postcode Lookup

You can perform a postcode lookup, using the required HTTPS request method, directly in the Java language.

codeimport java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
 
public class OpenPostcodesExample
{
    public static void main(String[] args) throws Exception
    {
        String url = "https://api.openpostcodes.com/v1/postcodes";
        String key = "openpostcodes_demo"; // Change to your API Key
        String postcode = "XA10XX";

        getPostcode(url, key, postcode);
    }

    // HTTP GET postcode request
    private static void getPostcode(String url, String key, String postcode) throws Exception
    {
        URL obj = new URL(url +"/"+ postcode + "?api_key=" + key);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
        con.setRequestMethod("GET");

        int resCode = con.getResponseCode();
        System.out.println("Sending postcode request: " + url);
        System.out.println("HTTP response code: " + resCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null)
        {
                response.append(inputLine);
        }
        in.close();

        // print result
        System.out.println(response.toString());
    }
}

In the example above you would replace the testing key with your own unique key and the postcode with the postcode to lookup.

jQuery

The quickest and easiest way to integrate postcode lookups on to your web application or page is simply to use our jQuery postcode plugin.

The plugin creates an input field for the postcode and a submit button to send the postcode to our lookup service. If the postcode is valid a dropdown menu is created, and populated with addresses relating to the postcode, allowing the user to select the appropriate address, once selected the address will be inserted into the form. If the supplied postcode is invalid or an error occurred an error will be displayed to the user.

The API returns addresses in a format which is recommended by Royal Mail, ensuring that any premise in the United Kingdom can be uniquely identify. This consists of 3 address lines, the town and postcode.

Installation

Download the plugin from GitHub and upload to your web server

code<script src="jquery.postcode.min.js"></script>

Implementation

Create a hassle free postcode search by creating a HTML div tag, where you want the form to be located. Then call the lookupPostcodeForm() function with your configuration, including your API key and address fields. In the example we use the testing API key.

code<script>
$('#postcode_lookup').lookupPostcodeForm({
    api_key: 'openpostcodes_demo', // Change to your API key
    output_fields:{
        line_1: '#line1',
        line_2: '#line2',
        line_3: '#line3',
        post_town: '#town',
        postcode: '#postcode'
    }
});
</script>

<div id="postcode_lookup"></div>

<label>First Address Line</label>
<input id="line1" type="text">

<label>Second Address Line</label>
<input id="line2" type="text">

<label>Third Address Line</label>
<input id="line3" type="text">

<label>Town</label>
<input id="town" type="text">

<label>Postcode</label>
<input id="postcode" type="text">

Check out our live example

Additional Address Data

You only need to setup 5 fields in order to identify any premise in the UK, however you can gain more information about each premise by using additional parameters supplied in the API response, these parameters can be obtained by including them in the output_fields object. Below is a list of all the available fields.

codeoutput_fields:
{
    "postcode": (string),                   // Postcode
    "postcode_inward": (string),            // Postcode Inward Code
    "postcode_outward": (string),           // Postcode Outward Code
    "post_town": (string),                  // Town
    "dependant_locality": (string),         // Dependant Locality
    "double_dependant_locality": (string),  // Double Dependant Locality
    "thoroughfare": (string),               // Thoroughfare
    "dependant_thoroughfare": (string),     // Dependant Thoroughfare
    "building_number": (string),            // Building Number
    "building_name": (string),              // Building Name
    "sub_building_name": (string),          // Sub Building Name
    "po_box": (string),                     // PO Box
    "department_name": (string),            // Department Name
    "organisation_name": (string),          // Organisation Name
    "udprn": (int),                         // Unique Delivery Point Reference Number
    "postcode_type": (string),              // Postcode Type
    "su_organisation_indicator": (string),  // Small Organisation Indicator
    "delivery_point_suffix": (string),      // Delivery Point Suffix
    "line_1": (string),                     // Address Line 1
    "line_2": (string),                     // Address Line 2
    "line_3": (string),                     // Address Line 3                     
    "longitude": (float),                   // Longitude
    "latitude": (float),                    // Latitude
    "eastings": (int),                      // Eastings
    "northings": (int)                      // Northings
}

More detailed information about the response fields here

To include them on your form add the field name to the output_fields. In the example below the organisation name (organisation_name) can be extracted from the API response and used in the form.

code<script>
$("#postcode_lookup").lookupPostcode({
    api_key: 'openpostcodes_demo',
    output_fields: {
        organisation_name: '#organisation',
        line_1: '#line1',
        line_2: '#line2',
        line_3: '#line3',
        post_town: '#town',
        postcode: '#postcode'
    }
});
</script>

<div id="postcode_lookup"></div>

<label>Organisation</label>
<input id="organisation" type="text">

<label>First Address Line</label>
<input id="line1" type="text">

<label>Second Address Line</label>
<input id="line2" type="text">

<label>Third Address Line</label>
<input id="line3" type="text">

<label>Town</label>
<input id="town" type="text">

<label>Postcode</label>
<input id="postcode" type="text">

Check out our live example

Advanced Implementation

For greater control over your implementation you may want to utilise the function below.

code$.openPostcodes.lookupPostcode(postcode, api_key, success[, error])

Function arguments breakdown

postcode
required    string The postcode requested for lookup
api_key
required    string For authentication, found in your account area
success
required    function Handler once the data has been successfully received
error
optional    function Handler if the request timed out

You can apply these parameters as shown in the example below.

code$.openPostcodes.lookupPostcode('XA10XX', 'openpostcodes_demo', function (data)
{
    // print first address to console
    console.log(data.result[0]); 
});

This will result in the following console output.

console{
    "postcode": "XA1 0XX",
    "postcode_inward": "0XX",
    "postcode_outward": "XA1",
    "post_town": "LONDON",
    "dependant_locality": "",
    "double_dependant_locality": "",
    "thoroughfare": "Oaks Avenue",
    "dependant_thoroughfare": "",
    "building_number": "",
    "building_name": "The Pavilion",
    "sub_building_name": "",
    "po_box": "",
    "department_name": "",
    "organisation_name": "",
    "udprn": 22088057,
    "postcode_type": "S",
    "su_organisation_indicator": "",
    "delivery_point_suffix": "2U",
    "line_1": "The Pavilion",
    "line_2": "Oaks Avenue",
    "line_3": "",
    "longitude": -0.087480458807402,
    "latitude": 51.426390555825,
    "eastings": 533062,
    "northings": 171444
}

Available jQuery Configuration Options

You can configure almost every aspect of how the jQuery plugin displays and executes in the background. Below is a list of the parameters.

debug_mode
boolean    default: false When true, the plugin will output errors and response codes from the API
lookup_interval
integer    default: 1000 The amount of time in milliseconds (ms) the lookup button will be disabled for after being clicked
input_class
string Class of the input field
input_label
string    default: "Enter your Postcode" Postcode input field placeholder
input_muted_style
string    default: "color:#CBCBCB;" Placeholder text style parameter value
button_class
string Class of the lookup button
button_label
string    default: "Find your Address" Lookup button label
button_disabled_message
string    default: "Fetching Addresses..." Lookup button label when disabled during the lookup_interval
dropdown_class
string Class of the address select dropdown
dropdown_select_message
string    default: "Select your Address" Sets the text of the first option on the address dropdown
error_message_class
string Class of the error message
error_message_default
string    default: "We were not able to your address from your postcode. Please input your address manually" Error message after a failed Postcode lookup
error_message_postcode_invalid
string    default: "Please recheck your postcode, it seems to be incorrect" Error message when supplying an invalid Postcode format
error_message_postcode_
not_found
string    default: "Your postcode could not be found. Please type in your address" Error message when a postcode does not exist
onLookupSuccess
function(data) Function is invoked once a successful lookup has been made. The 'data' argument is the API response. Please note that to our jQuery plugin using callbacks this function will also be invoked on 4xx errors, more information about this in the JSONP section of the Response Codes.
onLookupError
function() Function is invoked if an erroneous response is returned from the API, such as a timeout.
onAddressSelected
function() Function is invoked when the user selects an address from the, API populated, address dropdown field.

Source

jQuery Plugin

Node.js

We provide our own official open source, open licence package to lookup postcode data using NodeJS.

Installation

First install the package using the NPM (Node Package Manager).

codenpm install postcodes

Implementation

The example uses the Open Postcodes demo API key [openpostcode_demo], this will only successfully lookup testing postcodes. Change the example below to include your API key, then require the postcodes package. This will allow you to preform lookups using the Postcodes object.

codevar api_key = "openpostcodes_demo"
var Postcodes = require('postcodes')(api_key)

Usage

You can request postcode lookups using the lookupPostcode() function, its parameters are the postcode to lookup and the callback. Use one of our test postcodes to test your implementation.

codePostcodes.lookupPostcode("XA1 0XX", function (error, addresses)
{
    if (error)
    {
        // Add your own error handling...
        return error; 
    }
    
    if (addresses.length === 0)
    {
        console.log("Address array empty... postcode not found");
    }else{
        console.log(addresses); // print addresses to console
    }   
});

Source Code

Github

PHP

The example below demonstrates how to perform a postcode lookup with PHP without using any external or 3rd party libraries.

PHP Postcode Lookup

You can perform a postcode lookup, using the required HTTPS request method, with the PHP implementation of cURL.

code<?php
    // API settings
    $api_url     = 'https://api.openpostcodes.com/v1/postcodes/';
    $api_key     = 'openpostcodes_demo';
    $postcode    = 'XA1 0XX';

    // cURL request
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api_url . rawurlencode($postcode) . '?api_key='. $api_key);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response_raw = curl_exec($ch);
    curl_close($ch);
    
    // response format
    $response_decoded = json_decode($response_raw, true);
    $addresses = $response_decoded['result'];
    
    // print output
    print_r($addresses);

In the example above you would replace ($api_key) with your own API key and the ($postcode) with the postcode to lookup.

Python

The example below demonstrates how to perform a postcode lookup using Python without using any external or 3rd party libraries.

Python Postcode Lookup

You can perform a postcode lookup via a HTTPS request using urllib, httplib and json libraries in Python.

codeimport httplib, urllib, json

parameters = {"api_key": "openpostcodes_demo"}
postcode = "XA1 0XX"

conn = httplib.HTTPSConnection("api.openpostcodes.com:443")
conn.request("GET", "/v1/postcodes/%s?%s" % (urllib.quote(postcode), urllib.urlencode(parameters)))

addresses = json.load(conn.getresponse())['result']

In the example you must replace the api_key parameter with your key and the postcode variable with the requested postcode.

Ruby

Open Postcodes provides an open source and open licence library which can be found on GitHub, to allow you to request postcode lookups using Ruby. The follow documentation shows you how to implement our library.

Ruby Postcode Lookup

Installation

Our gem can be installed using rubygems.org

codegem install postcodes

Configuration

Require the gem in your code and pass your API key

coderequire 'postcodes'

Postcodes.api_key = "YOUR API KEY"

Usage

In order to return a postcode object containing all relevant premise addresses call the lookup method on the Postcodes::Postcode class, if the postcode is valid the request will be fulfilled.

codepostcode = Postcodes::Postcode.lookup "XA1 0XX"

Source Code

Github

Ruby on Rails

Open Postcodes provides an open source and open licence library which can be found on GitHub, to allow you to request postcode lookups using Ruby on Rails. The follow documentation shows you how to implement our library.

Ruby on Rails Postcode Lookup

Installation

Add this line to your gemfile and run bundle install.

codegem 'postcodes'

Configuration

In the example below we have used the Open Postcodes demo API key [openpostcodes_demo], this will only allow you to lookup testing postcodes. To lookup real postcodes you must sign up for an API key and replace the demo key in the example.

codePostcodes.api_key = "openpostcodes_demo"

Usage

To request a lookup call the lookup function on Postcodes::Postcode, as shown in the example below. Once successfully executed the function will return an object containing the related addresses.

codepostcode = Postcodes::Postcode.lookup "XA1 0XX"

postcode.addresses # an array containing all addresses relating to the provided postcode

Source Code

Github

Testing

All of our code examples and plugins use the demo API key [openpostcodes_demo], this key will only work with testing Postcodes. In order to process real postcodes you must purchase lookups from your account.

We provide test data which has been specifically created to return simulated successful and erroneous responses, this allows you to test your implementation is able to cope with an array of situations which may arise. All testing Postcode will not count against your account lookups.

Postcode Testing

There are no United Kingdom Postcodes which begin with an "X", which makes them an optimal postcode for testing your implementation. Below are a list of test postcodes which will return the stated outputs when queried.

Input HTTP Code Custom Code Message
XA1 0XX 200 2000 Successful
XA1 1XX 200 2000 Successful
XA1 2XX 200 2000 Successful
XB1 0XX 401 4010 Invalid Key
XB1 1XX 401 4011 Referer Excluded
XC1 0XX 402 4020 Lookups Exhausted
XC1 1XX 402 4021 Limit Reached
XD1 0XX 404 4040 Postcode Not Found
XE1 0XX 422 4220 Invalid Input
XF1 0XX 500 N/A N/A

Location Testing

We do not provide any specific longitude and latitude or additional parameters for location testing, because errors can be provoked by supplying parameters which do not match the method criteria. Shown below are examples of parameters which provoke the corresponding errors.

Parameter Value Codes (HTTP / Custom) Message
lonlat (empty) 422 / 4220 Invalid Longitude / Latitude
lonlat invalidformat 422 / 4220 Invalid Longitude / Latitude
radius (empty) 200 / 2000 (defaults to 100 metres)
radius invalidradius 200 / 2000 (defaults to 100 metres)
radius 100000 200 / 2000 (defaults to max 1000 metres)
limit (empty) 200 / 2000 (defaults to 100 results)
limit invalidlimit 200 / 2000 (defaults to 100 results)
limit 100000 200 / 2000 (defaults to max 150 results)

Changelog

We provide a log of changes, and accompanying dates, to the API. Any changes and improvements are backwards compatible within major versions, changes which break compatibility within major versions will be given a new API version number.

March 30, 2014

Original version of the API released Version 1 (v1)