# Python

> A client for Python 3.9 and later that only needs the standard library. One module, no dependencies.

Source: https://findort.ch/en/docs/python/

## Install

<p class="install"><span class="sign">pip install findort</span></p>

```python
from findort import Findort

findort = Findort(os.environ["FINDORT_KEY"], lang="en")
place = findort.geocode("Bundesplatz 3, Bern", country="ch")

if place:
    print(place.label, place.location.lat, place.location.lon)
```

On servers use a secret key `sk_…`.

## Creating a client

```python
```

| Argument | Type | Default | Description |
|---|---|---|---|
| `key` | str | | API key |
| `base_url` | str | `https://api.findort.ch` | API address |
| `lang` | str | | Language for all requests: `de`, `fr`, `it`, `en` |
| `country` | str or list | | Country filter for all searches: `"ch"` or `["ch", "li"]` |
| `timeout` | float | `8.0` | Time limit in seconds |
| `transport` | callable | | Your own HTTP function for tests: `(url, headers) -> (status, body_bytes)` |

## search

```python
    "Bahnhofstr 1 Zür",
    limit=5,
    types=["address", "poi"],
    near=(47.3769, 8.5417),
)
for place in places:
    print(place.label)
```

| Argument | Type | Description |
|---|---|---|
| `limit` | int | 1 to 20, default 5 |
| `lang` | str | language for this request only |
| `country` | str or list | country filter for this request only |
| `near` | `(lat, lon)` | prefer nearby results |
| `bbox` | `(minLon, minLat, maxLon, maxLat)` | strictly limit to a rectangle |
| `types` | str or list | only these [types](https://findort.ch/en/docs/response/#types) |

## reverse

```python
print(places[0].label if places else "nothing found")
```

Arguments: `limit`, `lang`, `radius` (kilometres, 0.01 to 50), `types`.

## geocode

The best match as a `Place`, or `None`. Takes the same arguments as `search`.

```python
```

## Place

`Place` is an immutable dataclass.

| Field | Type |
|---|---|
| `id`, `label`, `name`, `type`, `category` | str |
| `address` | dict with the [address fields](https://findort.ch/en/docs/response/#address) |
| `location` | `Location` with `lat` and `lon` |
| `bbox` | `tuple` as `(minLon, minLat, maxLon, maxLat)` or `None` |

Plus the shortcuts `street`, `housenumber`, `postcode`, `city` (city or locality) and `country_code`. They are `None` when the value is missing.

`Location.distance_to()` returns the straight-line distance in kilometres:

```python
thun = findort.geocode("Bahnhof Thun")
print(f"{bern.location.distance_to(thun.location):.1f} km")
```

## Errors

On an error response the client raises `FindortError` with `status` (HTTP) and `code`. If the server is unreachable, `code` is `network_error` and `status` is `0`.

```python
from findort import FindortError

try:
    findort.search("Bern")
except FindortError as e:
    if e.code == "rate_limited":
        time.sleep(2)
```

All codes are listed under [errors](https://findort.ch/en/docs/errors/).
