Metadata-Version: 2.5
Name: lodapi
Version: 0.0.3
Summary: Ergonomic Python SDK for the Lodapi REST API (LoD2 buildings, terrain, 3D tiles).
Project-URL: Homepage, https://lodapi.de
Project-URL: Documentation, https://lodapi.de/docs
Author-email: scenerii GmbH <konsti@scenerii.com>
License: Apache-2.0
Keywords: 3d-tiles,citygml,geospatial,gis,lod2,lodapi,terrain
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: GIS
Requires-Python: >=3.10
Requires-Dist: httpx>=0.27
Requires-Dist: pydantic>=2
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: respx>=0.21; extra == 'dev'
Provides-Extra: geo
Requires-Dist: geopandas>=0.14; extra == 'geo'
Requires-Dist: shapely>=2.0; extra == 'geo'
Description-Content-Type: text/markdown

# lodapi — Python SDK

Ergonomic Python client for the [Lodapi](https://lodapi.de) REST API: federated
LoD2 buildings across all 16 German Bundesländer, DGM terrain elevation, and 3D
Tiles tileset discovery.

> **v0 / unstable.** This is `0.0.3`. The public surface may change before
> `0.1`. Pin an exact version if you depend on it.

## Install

```bash
pip install lodapi
pip install lodapi[geo]     # adds geopandas/shapely → .to_geodataframe()
```

Requires Python 3.10+.

## Quickstart

```python
from lodapi import Client

# api_key is optional — without one you use the anonymous free tier
# (capped at 1,000 requests per IP per day, see "Auth and the free tier").
c = Client(api_key="lod_...")

# One page of buildings for a WGS84 bbox (minLon, minLat, maxLon, maxLat):
page = c.buildings(bbox=(7.0, 50.9, 7.1, 51.0), limit=500)
print(page.count, page.next_cursor)

# Transparent cursor pagination — iterate every feature across all pages:
for feature in c.buildings.iter(bbox=(7.0, 50.9, 7.1, 51.0)):
    ...

# Or page-by-page:
for p in c.buildings.pages(bbox=(7.0, 50.9, 7.1, 51.0)):
    ...

# Single building + its roof surfaces (gmlid from any feature's properties):
b = c.buildings.get("DEHE06200001dUNH")
roof = c.buildings.roof("DEHE06200001dUNH")

# Stream a binary GLB of the bbox to disk (or get bytes back with out=None):
c.buildings.glb(bbox=(13.40, 52.51, 13.41, 52.52), out="city.glb")

# Terrain:
h = c.terrain.elevation(lat=50.94, lon=7.05)         # ElevationResponse
prof = c.terrain.profile(coords=[(7.0, 50.9), (7.1, 51.0)], samples=100)
c.terrain.datasets()                                  # DGM raster datasets
c.terrain.mesh_datasets()                             # quantized-mesh tilesets

# Datasets + 3D Tiles:
c.datasets()                                          # LoD2 datasets per BL
res = c.tilesets(bbox=(6.93, 50.92, 7.02, 50.96))     # tilesets in a bbox
ts = res.tilesets[0]
c.tilesets.get(ts.tileset_id)                         # one tileset
c.tilesets.tileset_json(ts.tileset_id)                # raw 3D-Tiles root (dict)

c.close()   # or use `with Client(...) as c: ...`
```

Tileset ids are **UUIDs** and belong to one snapshot — discover them via
`c.tilesets(bbox=...)` (or use `ts.tileset_url`, which points straight at the
`tileset.json` on the CDN) instead of hard-coding an id.

There is **no `bl` parameter** — federation across the 16 Bundesländer is
server-side and automatic. A bbox tuple `(minLon, minLat, maxLon, maxLat)` is
serialized to the API's `"minLon,minLat,maxLon,maxLat"` string for you; you may
also pass an already-formatted string.

## What `buildings()` returns

`c.buildings(...)` is **surface-level**: one GeoJSON feature is one *surface*,
not one building. `properties.surface_class` is the CityGML object class —
`709` wall, `710` ground, `712` roof — and all surfaces of a building share the
same `gmlid` / `building_id`. Group them to get whole buildings:

```python
from collections import defaultdict

page = c.buildings(bbox=(8.6995, 50.1225, 8.7005, 50.1235))
buildings = defaultdict(list)
for f in page.features:
    buildings[f["properties"]["gmlid"]].append(f)
```

`c.buildings.get(gmlid)` returns the same building as a single aggregated
geometry, `c.buildings.roof(gmlid)` only its roof surfaces (with slope and
azimuth). Per-building attributes (roof type, function, …) are not part of the
slim dataset the bbox endpoint serves.

## Attribution: the `lodapi` envelope

Every buildings response carries a `lodapi` block next to the GeoJSON:

```python
page.lodapi.next                 # opaque cursor (same as page.next_cursor)
for a in page.lodapi.attribution:
    print(a.bundesland_code, a.license_id, a.requires_attribution)
    print(a.attribution_text, a.attribution_url, a.license_url)
```

The list has **one entry per Bundesland present in that response** — a bbox on
a state border returns two, with different licences (`dl-de-zero-2.0` needs no
credit, `dl-de-by-2.0` does). Where `requires_attribution` is `True`, display
that entry's `attribution_text`. `GET /v1/attribution` returns the same blocks
for all data products at once, without a bbox.

## Auth and the free tier

Anonymous works — no key, no signup:

```python
c = Client()                       # no api_key
```

Anonymous traffic is capped at **1,000 requests per IP per UTC day**. Beyond it
the API answers `429` and the SDK raises `RateLimitError` (the problem document
carries `key_url` and a `Retry-After` header). Discovery calls
(`/v1/datasets`, `/v1/attribution`) and the key endpoints don't count against
the cap.

With a key, pass it to the constructor; it is sent as the `X-API-Key` header.
Keys have the shape `lod_` + 32 lowercase chars (see ADR-0014). A
malformed/unknown/revoked key raises `AuthError` on the first call.

### Getting a key

- **Browser:** [lodapi.de/key](https://lodapi.de/key).
- **curl:**

  ```bash
  curl -s -X POST https://api.lodapi.de/v1/keys/trial \
       -H 'content-type: application/json' \
       -d '{"source": "sdk"}'
  # → {"key": "lod_…", "tier": "trial", "expires_at": …, "limits": {…}}
  ```

  The plaintext key is returned **once** and is not recoverable. A trial key is
  valid for **7 days** with **5,000 requests/day** (soft), read-only. `email`
  is an optional second body field for lead attribution; `source` is a free
  campaign slug. Both are optional.

### Quota headers

```python
c.buildings(bbox=(...))
q = c.last_quota
q.used, q.limit, q.remaining   # keyed soft quota (X-Lodapi-Quota-*, ADR-0014)
q.keyless_remaining            # anonymous calls left today (X-Keyless-Remaining)
```

`used`/`limit` come from the **keyed** quota, which is *soft* — exceeding it is
counted, not blocked — and are `None` for anonymous calls or keys without a
configured quota. `keyless_remaining` is the enforced anonymous budget and is
`None` on keyed calls (or when the server sends no header). Watch it in batch
scripts to see the wall coming instead of running into it.

## GLB defaults

`c.buildings.glb(...)` applies a neutral, glTF-consumption-friendly default set
for frame/origin/rotation. These differ from the raw REST-API defaults: the API
itself does **not** rotate, while the SDK rotates Z-up → Y-up so the model
stands upright out-of-the-box in Blender / three.js / model-viewer / Cesium
(glTF is Y-up per spec).

| param          | raw API default | SDK default | why the SDK differs                       |
|----------------|-----------------|-------------|-------------------------------------------|
| `target_frame` | `utm`           | `utm`       | metric, scale-true (not MapLibre-bound)   |
| `origin`       | `center`        | `center`    | model centred on the origin               |
| `rotate_x`     | `0`             | `-90`       | Z-up → Y-up for glTF-spec conformance     |
| `rotate_z`     | `0`             | `0`         | no extra spin around the vertical axis    |

All other GLB params (`z_base`, `compression`, `colorize_roofs`,
`merge_buildings`, `include_ground`, `weld_tolerance_m`) pass through to the
API's own defaults when omitted. Every default is overridable per call:

```python
# Reproduce the scenerii-App view (MapLibre-aligned):
c.buildings.glb(
    bbox=(13.40, 52.51, 13.41, 52.52),
    target_frame="mercator", origin="corner", rotate_x=-90, rotate_z=-90,
)

# Get raw geospatial Z-up (no rotation, matches the raw API):
c.buildings.glb(bbox=(13.40, 52.51, 13.41, 52.52), rotate_x=0)
```

With a path in `out`, missing parent directories are created and the file is
written atomically (streamed to `<path>.part`, renamed on success).

## Errors

All API errors follow RFC 7807 `application/problem+json` (base
`https://lodapi.de/errors`). The SDK parses the document onto a typed exception:

```python
from lodapi import LodapiError, AuthError, NotFoundError, RateLimitError, ApiError

try:
    c.buildings.get("NOPE")
except NotFoundError as exc:
    print(exc.status, exc.title, exc.detail, exc.instance)
```

- `AuthError` — 401
- `NotFoundError` — 404
- `RateLimitError` — 429: the anonymous daily cap (get a key), or too many
  trial-key mints from one IP
- `ApiError` — any other non-2xx
- `LodapiError` — base class + transport/network errors

Transient 5xx and network errors are retried (default 2 retries, exponential
backoff). 4xx are never retried.

## GeoDataFrame support (`geo` extra)

With `pip install lodapi[geo]`, building/roof FeatureCollections convert to a
`geopandas.GeoDataFrame` (CRS `EPSG:4326`):

```python
page = c.buildings(bbox=(7.0, 50.9, 7.1, 51.0))
gdf = page.to_geodataframe()      # this page's features
roof = c.buildings.roof("DEHE06200001dUNH")
roof.to_geodataframe()
```

An empty result yields an empty GeoDataFrame (with a `geometry` column), so
pages can be concatenated without a special case. Without the extra,
`to_geodataframe()` raises `ImportError` with an install hint; the rest of the
SDK works fine.

## Configuration

```python
Client(
    api_key=None,                      # optional lod_* key
    base_url="https://api.lodapi.de",  # override for staging/local
    timeout=30.0,                      # per-request seconds
    max_retries=2,                     # transient 5xx/network only
)
```

## Development

Sources live in the Lodapi repo (`code/sdk-python/`); tests mock all HTTP with
`respx` and run via `uv run --extra dev pytest`.

## License

Apache-2.0. © scenerii GmbH.
