# Swiss Address Validation & Geocoding (geo.admin.ch) (`najx/swiss-address-geocoder`) Actor

Validate, normalise and geocode Swiss addresses with the official swisstopo data: postal code, municipality and BFS number, canton, building identifiers (EGID / EGAID), WGS84 and LV95 coordinates, building facts from the federal register, and reverse geocoding from coordinates.

- **URL**: https://apify.com/najx/swiss-address-geocoder.md
- **Developed by:** [Najim Abdelmoula](https://apify.com/najx) (community)
- **Categories:**
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $2.00 / 1,000 address results

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

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

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
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.
Actors are written with capital "A".

## 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.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

### What does Swiss Address Validation & Geocoding do?

**Swiss Address Validation & Geocoding** turns a free-text Swiss address into its **official, normalised form** with every identifier you need to join it to other data: **postal code, locality, municipality with its BFS number, canton, building identifier (EGID), address identifier (EGAID), WGS84 and LV95 coordinates**, plus facts about the building from the Federal Register of Buildings and Dwellings (construction year, floors, dwellings, category). It also resolves **postal codes**, **municipality names**, and does **reverse geocoding** from coordinates. It is a **Swiss geocoding API** built on the official swisstopo data through [geo.admin.ch](https://api3.geo.admin.ch).

It does not scrape private websites and processes no personal data: it only ever sees the address text or coordinates you send.

### Why use Swiss Address Validation & Geocoding?

Swiss addresses are tricky: postal codes span several municipalities, localities are not municipalities, three official languages, and the identifiers that matter (BFS municipality number, EGID) never appear on a letter.

- ✅ **Official data, official identifiers**: results come from swisstopo's federal address directory and the federal building register, not from a commercial map provider.
- 🧭 **One call, many keys**: BFS number for statistics and premium regions, EGID for building-level joins, LV95 for Swiss GIS, WGS84 for web maps.
- 🏢 **Building facts included**: year built, floors, dwellings, category and class, heating and energy source codes, parcel.
- 🔁 **Both directions**: address → identifiers and coordinates, or coordinates → nearest building and municipality.
- 🎯 **Match quality you can act on**: `exact`, `probable`, `ambiguous` or `none` for every row, with optional alternative candidates.
- 🤖 **Automation-friendly**: batch up to 1,000 queries per run, call it from n8n, Make, Zapier or the Apify API, or expose it to AI agents through the Apify MCP server.

Typical users: CRMs and e-commerce checkouts cleaning customer addresses, insurers and property managers keying buildings by EGID, solar and energy companies, real-estate and proptech tools, data teams joining addresses to federal statistics, and AI assistants answering "which municipality is this address in".

### What data does it return?

| Field | Type | Description |
| --- | --- | --- |
| `status` / `matchQuality` | string | `ok`, `not_found`, `error`; `exact`, `probable`, `ambiguous`, `none` |
| `formattedAddress` | string | "Avenue de Milan 3, 1007 Lausanne" |
| `street` / `houseNumber` / `postalCode` / `locality` | string | Normalised address parts |
| `municipality` / `municipalityBfs` / `canton` | string / integer | Municipality name, federal BFS number, two-letter canton |
| `egid` / `edid` / `egaid` | integer | Building, entrance and address identifiers of the federal registers |
| `isOfficialAddress` | boolean | Whether the address is the official one for the entrance |
| `lat` / `lon` | number | WGS84 coordinates |
| `lv95East` / `lv95North` | number | Swiss LV95 coordinates (EPSG:2056) |
| `building` | object | `constructionYear`, `floors`, `dwellings`, `status`, `category`, `class`, `footprintM2`, heating and energy codes, `parcel` |
| `source` | string | "© Data: swisstopo, api3.geo.admin.ch" |

### How to validate and geocode Swiss addresses

1. Open the Actor and paste your **queries**: plain strings ("Bahnhofstrasse 1, 8001 Zürich", "8914", "Biel", "46.5165, 6.6242") or objects with an `id` so you can join results back to your data.
2. Leave **mode** on auto, or force `address`, `postalCode`, `municipality` or `reverse`.
3. Set **candidates per query** to more than 1 if you want alternatives for ambiguous inputs.
4. Click **Start**. Each query yields one row (or one per candidate) in the Output tab.
5. Download as JSON, CSV or Excel, or read the dataset from your automation.

#### How is match quality decided?

`exact`: every word of your query is found in the official address and the search engine did not need fuzzy matching. `probable`: most words match, or fuzzy matching was needed (typo, "Place" instead of "Avenue"). `ambiguous`: several candidates score equally, for example a street without a house number or a postal code shared by several localities. `none`: nothing found. Rows with `not_found` are free.

#### Municipality versus locality

The locality is the name printed after the postal code; the municipality is the political entity with the BFS number. They often differ (locality Aeugstertal, municipality Aeugst am Albis). The Actor returns both.

### How much does it cost?

The Actor is **paid per result row** (see the pricing box on this page). A query with one candidate is one result; `not_found` and error rows are free. Validating 1,000 addresses costs a couple of dollars, well below commercial geocoders, and the swisstopo data is authoritative.

### Input

See the Input tab for all options. Example:

```json
{
  "queries": [
    {"id": "hq", "address": "Avenue de Milan 3, 1007 Lausanne"},
    {"id": "zip", "postalCode": "8914"},
    {"id": "city", "municipality": "Biel"},
    {"id": "point", "lat": 46.51649, "lon": 6.62416}
  ],
  "maxCandidates": 1,
  "includeBuilding": true
}
```

### Output

You can download the dataset in JSON, CSV, Excel or HTML formats. One resolved address:

```json
{
  "id": "hq",
  "status": "ok",
  "matchQuality": "exact",
  "rank": 1,
  "formattedAddress": "Avenue de Milan 3, 1007 Lausanne",
  "street": "Avenue de Milan",
  "houseNumber": "3",
  "postalCode": "1007",
  "locality": "Lausanne",
  "municipality": "Lausanne",
  "municipalityBfs": 5586,
  "canton": "VD",
  "country": "CH",
  "egid": 886051,
  "edid": 0,
  "egaid": 100496355,
  "isOfficialAddress": true,
  "lat": 46.516494,
  "lon": 6.624155,
  "lv95East": 2537495.616,
  "lv95North": 1152010.746,
  "building": {"status": "existing", "category": "residential only", "class": "multi-family house", "constructionYear": 1903, "floors": 5, "dwellings": 10},
  "source": "© Data: swisstopo, api3.geo.admin.ch",
  "errors": []
}
```

### Using the Actor from code and AI agents

Call it through the [Apify API](https://docs.apify.com/api/v2) in any language, or expose it to Claude, ChatGPT, Cursor or any MCP client through the [Apify MCP server](https://mcp.apify.com/). Example with the Python client:

```python
from apify_client import ApifyClient

client = ApifyClient("<YOUR_API_TOKEN>")
run = client.actor("<ACTOR_ID>").call(run_input={  # Actor ID or "username/name" from the API tab
    "queries": [{"id": "1", "address": "Bahnhofstrasse 1, 8001 Zürich"}],
})
for row in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(row["matchQuality"], row["formattedAddress"], row["municipalityBfs"], row["egid"], row["lat"], row["lon"])
```

### Data source, fair use and privacy

- Data: Federal Office of Topography swisstopo, through the public geo.admin.ch REST API (federal address directory, Federal Register of Buildings and Dwellings, swissBOUNDARIES3D, postal code directory). Results carry the required attribution "© Data: swisstopo".
- Fair use: the Actor paces its requests (about 8 per second at most, 1,000 queries per run) to respect the fair-use policy of the federal spatial data infrastructure. For very large batches, split them across runs.
- Privacy: queries are processed in memory and written only to your run's dataset. Addresses of buildings are public data; do not send names or other personal data in the query text.

### Frequently asked questions

#### Does it cover Liechtenstein?

Yes, the federal address directory includes Liechtenstein (country code LI).

#### Why is my street returned as ambiguous?

Without a house number, every building on the street is an equally good match. Add the number, or set `maxCandidates` to see the alternatives.

#### Can I get the premium region, the electricity tariff or the building register data for this address?

This Actor already returns the building register facts. For premium regions and tariffs, chain it with the companion Swiss data Actors from the same author, which take the BFS municipality number as input.

#### Something looks wrong

Open an issue in the **Issues** tab with the query you used.

### Development

Python 3.12, Apify SDK, no other dependency: `geocoder_actor/geoadmin.py` is a minimal client for the geo.admin.ch REST API, `normalize.py` holds the parsing and scoring logic. `pytest -m "not live"` runs on recorded API responses; `pytest -m live` calls the real API; `apify run` runs the Actor locally.

# Actor input Schema

## `queries` (type: `array`):

One entry per lookup: a string ("Avenue de Milan 3, 1007 Lausanne", "8914", "Lausanne", "46.5165, 6.6242") or an object {"id": "...", "address": "..."} / {"postalCode": "1003"} / {"municipality": "Biel"} / {"lat": 46.5165, "lon": 6.6242}. Up to 1,000 per run.

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

auto detects per query (4 digits = postal code, two decimals = coordinates, otherwise address, falling back to municipality). Force a mode when your input is uniform.

## `maxCandidates` (type: `integer`):

1 returns the best match only. Higher values return alternatives (each candidate is one billable result), useful for ambiguous inputs such as a street without house number or a postal code shared by several localities.

## `includeBuilding` (type: `boolean`):

Adds data from the Federal Register of Buildings and Dwellings (RegBL / GWR): construction year, floors, dwellings, category, class, heating and energy source codes, parcel, LV95 coordinates. One extra API call per address.

## `language` (type: `string`):

Language used by geo.admin.ch for municipality and locality labels in reverse lookups.

## Actor input object example

```json
{
  "queries": [
    {
      "id": "hq",
      "address": "Avenue de Milan 3, 1007 Lausanne"
    },
    {
      "id": "zip",
      "postalCode": "8914"
    },
    {
      "id": "city",
      "municipality": "Biel"
    },
    {
      "id": "point",
      "lat": 46.51649,
      "lon": 6.62416
    }
  ],
  "mode": "auto",
  "maxCandidates": 1,
  "includeBuilding": true,
  "language": "fr"
}
```

# Actor output Schema

## `addresses` (type: `string`):

No description

# 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 = {
    "queries": [
        {
            "id": "hq",
            "address": "Avenue de Milan 3, 1007 Lausanne"
        },
        {
            "id": "zip",
            "postalCode": "8914"
        },
        {
            "id": "city",
            "municipality": "Biel"
        },
        {
            "id": "point",
            "lat": 46.51649,
            "lon": 6.62416
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("najx/swiss-address-geocoder").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 = { "queries": [
        {
            "id": "hq",
            "address": "Avenue de Milan 3, 1007 Lausanne",
        },
        {
            "id": "zip",
            "postalCode": "8914",
        },
        {
            "id": "city",
            "municipality": "Biel",
        },
        {
            "id": "point",
            "lat": 46.51649,
            "lon": 6.62416,
        },
    ] }

# Run the Actor and wait for it to finish
run = client.actor("najx/swiss-address-geocoder").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 '{
  "queries": [
    {
      "id": "hq",
      "address": "Avenue de Milan 3, 1007 Lausanne"
    },
    {
      "id": "zip",
      "postalCode": "8914"
    },
    {
      "id": "city",
      "municipality": "Biel"
    },
    {
      "id": "point",
      "lat": 46.51649,
      "lon": 6.62416
    }
  ]
}' |
apify call najx/swiss-address-geocoder --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,najx/swiss-address-geocoder"
        }
    }
}

```

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/YPBTOGJ9eVvpqVpPH/builds/etg7sCeglQNGCONBA/openapi.json
