# Uk Postcode Lookup Scraper (`b2b_lead_generation/uk-postcode-lookup-scraper`) Actor

Bulk geocode UK postcodes or find nearest locations from coordinates. Export enriched location data including district, ward, and constituency directly to CSV, JSON, or Excel.

- **URL**: https://apify.com/b2b_lead_generation/uk-postcode-lookup-scraper.md
- **Developed by:** [B2B Lead Generation](https://apify.com/b2b_lead_generation) (community)
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $2.99 / 1,000 results

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## UK Postcode Lookup: Bulk Geocode

<p align="center">
  <img src="https://imgur.com/U0HWKAn.png" alt="UK Postcode Lookup" style="max-width:100%; border-radius:14px; width:680px;" />
</p>

Lookup UK postcodes for a batch of location codes, or quickly find the nearest postcode using latitude and longitude coordinates. Designed to handle data in bulk, this tool processes entries efficiently and outputs structured details including geographical coordinates, administrative districts, wards, and parliamentary constituencies. Results can easily be exported to CSV, JSON, or Excel.

Instead of manually checking postcodes one by one, you can convert lists in bulk and get accurate, structured location data for every match.

### Use Cases

- **Address lists:** Convert postcodes into latitude and longitude coordinates for mapping and spatial analysis.
- **Store & location search:** Reverse geocode coordinates to discover the nearest postcode, ward, and district around a specific location.
- **Constituency work:** Retrieve parliamentary constituency names and local administrative districts alongside your location data.
- **Spreadsheet cleanup:** Export results directly to JSON, CSV, or Excel to join enriched spatial data back to your primary dataset.
- **Automated updates:** Run scheduled lookups whenever mailing or store lists change.

### Extracted Data Points

The tool gathers key location metadata for each entry, including:

- Standardized UK postcode
- Latitude and longitude coordinates
- British National Grid eastings and northings
- Admin district, ward, parish, and county
- Country and electoral region
- Parliamentary constituency (including updated 2024 boundaries)
- Health authority (NHS), CCG, and primary care trust references
- Index of Multiple Deprivation (IMD) rank

### Input Options

| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
| `mode` | String | `lookup` | Use `lookup` to search postcodes, or `reverse` to find postcodes near lat/lon points. |
| `postcodes` | Array | `["SW1A1AA"]` | List of UK postcodes (one per line). Used in lookup mode. |
| `reverse` | Array | `[]` | List of objects containing `lat` and `lon`. Used in reverse mode. |
| `maxItems` | Integer | `100` | Maximum number of rows to retrieve (up to 1,000). |
| `timeoutSecs` | Integer | `300` | Overall run limit in seconds. |
| `requestTimeoutSecs` | Integer | `30` | Timeout per request in seconds. |

#### Example Input (Lookup Mode)

```json
{
    "mode": "lookup",
    "postcodes": ["SW1A1AA", "EC1A1BB"],
    "maxItems": 100,
    "timeoutSecs": 300,
    "requestTimeoutSecs": 30
}

```

#### Example Input (Reverse Mode)

```json
{
    "mode": "reverse",
    "reverse": [{ "lat": 51.501, "lon": -0.1416 }],
    "maxItems": 10
}

```

### Output Format

```json
{
    "postcode": "SW1A 1AA",
    "quality": 1,
    "eastings": 529090,
    "northings": 179645,
    "country": "England",
    "nhs_ha": "London",
    "longitude": -0.141563,
    "latitude": 51.50101,
    "european_electoral_region": "London",
    "primary_care_trust": "Westminster",
    "region": "London",
    "lsoa": "Westminster 018C",
    "msoa": "Westminster 018",
    "incode": "1AA",
    "outcode": "SW1A",
    "parliamentary_constituency": "Cities of London and Westminster",
    "parliamentary_constituency_2024": "Cities of London and Westminster",
    "senedd_constituency": null,
    "senedd_constituency_no": null,
    "admin_district": "Westminster",
    "parish": "Westminster, unparished area",
    "admin_county": null,
    "date_of_introduction": "198001",
    "date_of_termination": null,
    "index_of_multiple_deprivation": 24862,
    "admin_ward": "St James's",
    "ced": null,
    "ccg": "NHS West and North London",
    "nuts": "Westminster",
    "pfa": "Metropolitan Police"
}

```

### Output Fields

- `postcode`: Standard formatted UK postcode.
- `longitude` / `latitude`: WGS84 geographic coordinates.
- `eastings` / `northings`: British National Grid spatial references.
- `country`: Country name (e.g., England, Scotland, Wales, Northern Ireland).
- `region`: Geographical region.
- `admin_district`: Local authority district name.
- `admin_ward`: Local electoral ward name.
- `parliamentary_constituency`: Westminster constituency.
- `parliamentary_constituency_2024`: Post-2024 revised constituency boundary name.
- `incode` / `outcode`: Inward and outward postcode components.
- `index_of_multiple_deprivation`: Relative deprivation rank score.

### How It Works

1. Reads the selected mode (`lookup` or `reverse`) and prepares batch parameters.
2. In lookup mode, postcodes are processed in efficient batches of up to 100 entries. In reverse mode, coordinates are mapped directly.
3. Automatically retries temporary connection issues or rate limits using polite retry intervals.
4. If an invalid or unresolvable postcode is encountered, an error status is recorded for that specific line while continuing through the rest of your dataset uninterrupted.
5. Once complete, your dataset can be downloaded as JSON, CSV, or Excel.

### Frequently Asked Questions

**How many postcodes can I process at once?**

The default limit per run is set to 100 rows, but you can increase `maxItems` up to 1,000 rows per run.

**What happens if a postcode is invalid or not found?**

Invalid postcodes or unresolvable coordinates generate an error entry explaining the issue. The process continues seamlessly so the rest of your input list is completed.

**Can I convert coordinates back into postcodes?**

Yes. Set `mode` to `reverse` and pass latitude and longitude points in the `reverse` array.

***

### Legal & Compliance

#### Trademark Notice

UK Postcode and related names, logos, and trademarks belong to their respective owners. Their mention in this documentation is strictly to identify compatibility and data utility, and does not imply affiliation, sponsorship, or endorsement.

#### Disclaimer

This tool is an independent utility and is not affiliated with, endorsed by, or officially connected to third-party data providers. Users are responsible for ensuring their usage complies with relevant terms of service, attribution requirements, and local regulations.

#### Is web scraping legal?

This tool collects publicly available location data without bypassing access controls. Collecting public data is standard practice, but proper compliance requires considering how the data is used:

- **Personal data:** Ensure that dataset usage respects regional privacy regulations such as the GDPR or CCPA when combining outputs with personal user records.
- **Copyright & Terms:** Respect the terms of use, usage limits, and licensing terms set by the data source.
- **Legal advice:** This summary is provided for general informational purposes and does not constitute formal legal counsel.

# Actor input Schema

## `mode` (type: `string`):

Lookup turns UK postcodes into coordinates and admin areas. Reverse finds postcodes near latitude and longitude.

## `postcodes` (type: `array`):

UK postcodes to look up, one per line. Spaces are optional. Used when mode is lookup.

## `reverse` (type: `array`):

Points to reverse geocode when mode is reverse. Each object needs lat and lon, for example {"lat": 51.501, "lon": -0.1416}.

## `maxItems` (type: `integer`):

Maximum dataset rows for this run, including error rows. Values above 1000 are clamped to 1000.

## `timeoutSecs` (type: `integer`):

Stop the run after this many seconds. In-flight retries still finish, then no further requests are sent.

## `requestTimeoutSecs` (type: `integer`):

Seconds to wait for a single postcodes.io response before treating it as a timeout.

## `proxyConfiguration` (type: `object`):

Optional proxy for postcodes.io requests. Leave Apify Proxy off unless you have a reason to route traffic. Do not use proxies to get around source limits.

## Actor input object example

```json
{
  "mode": "lookup",
  "postcodes": [
    "SW1A1AA"
  ],
  "reverse": [
    {
      "lat": 51.501,
      "lon": -0.1416
    }
  ],
  "maxItems": 100,
  "timeoutSecs": 300,
  "requestTimeoutSecs": 30,
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}
```

# Actor output Schema

## `dataset` (type: `string`):

Open the full postcode dataset in Apify.

## `items` (type: `string`):

JSON items from the default dataset.

## `csv` (type: `string`):

Download the postcode rows as CSV.

## `excel` (type: `string`):

Download the postcode rows as Excel.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "postcodes": [
        "SW1A1AA"
    ],
    "reverse": [],
    "proxyConfiguration": {
        "useApifyProxy": false
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("b2b_lead_generation/uk-postcode-lookup-scraper").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "postcodes": ["SW1A1AA"],
    "reverse": [],
    "proxyConfiguration": { "useApifyProxy": False },
}

# Run the Actor and wait for it to finish
run = client.actor("b2b_lead_generation/uk-postcode-lookup-scraper").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "postcodes": [
    "SW1A1AA"
  ],
  "reverse": [],
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}' |
apify call b2b_lead_generation/uk-postcode-lookup-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,b2b_lead_generation/uk-postcode-lookup-scraper"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/HIzUYquNfd720nCsN/builds/enAzdSFvDayJBSDTz/openapi.json
