Metadata-Version: 2.4
Name: publictransport
Version: 0.1.2
Requires-Dist: httpx>=0.28
License-File: LICENSE-APACHE
License-File: LICENSE-MIT
License-File: NOTICE
Summary: Client for public transport APIs: EFA, MOTIS, TRIAS, OJP, HAFAS and OpenTripPlanner
License-Expression: MIT OR Apache-2.0
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Documentation, https://kiliankoe.github.io/publictransport/
Project-URL: Repository, https://github.com/kiliankoe/publictransport

<!-- ANCHOR: site -->
# publictransport

A Python client for public transport APIs. It uses a shared model for stops, departures and trips that covers several server types, so an application can query any supported network the same way. It supports servers that speak EFA (used by many German transport associations), MOTIS (the routing engine behind [Transitous](https://transitous.org)), TRIAS 1.2, OJP 1.0, HAFAS mgate (the interface behind many operators' apps) and OpenTripPlanner 2 with its Transmodel API.

The package wraps the Rust library of the same name. The Rust code builds the requests and parses the answers, and [httpx](https://www.python-httpx.org) sends them. Install it with `uv add publictransport` or `pip install publictransport`; there are wheels for Linux (glibc), macOS and Windows on x86-64, and for the first two on ARM.

```python
from publictransport import BundledNetwork, Client, LocationKind

vvo = BundledNetwork.VVO_EFA.network()

with Client(user_agent="my-app/1.0 (+https://example.org)") as client:
    stops = client.locations(vvo, "Hauptbahnhof", kinds=[LocationKind.STOP])
    for departure in client.departures(vvo, stops[0], limit=10):
        # The time on the clocks at the stop, where its time zone is known.
        time = departure.stop.local_time(departure.scheduled_time)
        print(
            f"{time:%H:%M}" if time else "?", departure.line.name, departure.direction
        )

    found = client.trips(vvo, stops[0], stops[1])
    more = client.trips(vvo, stops[0], stops[1], page=found.later)
```

The [documentation](https://kiliankoe.github.io/publictransport/python.html) has this guide with a short program for each kind of request, which are also in [examples](https://github.com/kiliankoe/publictransport/tree/main/examples/python).

`AsyncClient` has the same methods as coroutines. A stop or a place is a `Location` from a search, a departure or a trip, or an ID as text; a place in `trips` can be a `Coordinate` too. A location that another network returned works as well: for a trip always if it has a coordinate, for departures where the asked network can name the stop, which EFA, TRIAS and OJP can for stops with a global ID. Each method also takes a query object (`LocationQuery`, `DeparturesQuery`, `TripsQuery`) in place of the plain values, which is what the Rust library works with.

`BundledNetwork` names the networks that ship with the package. `Registry.bundled()` holds them all, for a list to choose from: `get("vvo-efa")` finds one by its ID as text, and `covering(Coordinate(...))` lists the networks for a position, each with the tier of its coverage there. A `Network` can also be written by hand, as `Network(id=..., name=..., endpoint=..., protocol=Protocol.EFA, timezone="Europe/Berlin")`, and `network_from_json(id, json)` reads further ones from entries in the format of [transport-apis](https://github.com/public-transport/transport-apis).

Times are timezone-aware `datetime` objects in UTC. `Location.local_time(time)` gives one as the clocks at that location show it, with the UTC offset that holds there at that time, or `None` where no time zone is known for it. It is for showing a time; calculate with the UTC values. A time in a query has to be timezone-aware too, in any zone. An EFA network needs its `timezone` to send a query time. A TRIAS or OJP network needs a `requestor_ref`, which public servers document, e.g. `OpenService`. A HAFAS network needs `hafas=HafasOptions(...)` and its `timezone`; the bundled ones have both. Entur asks every client for its name in the header `ET-Client-Name` (`company-application`) and limits clients without it, so add it to the bundled network: `entur.headers.append(Header(name="ET-Client-Name", value="mycompany-myapp"))`. A network of that protocol searches for locations on the geocoder named in `geocoder=`, and its answer to `trips` can be empty at night and still have a `later` reference to follow. A server that wants a key in an HTTP header gets it through `Network(headers=[Header(...)])`.

`trips` returns a `Trips` record: the list is in `trips`, and `earlier` and `later` are references for more. Pass one as `page` with the same other arguments to continue the search.

Failures that the server or the query cause are raised as subclasses of `publictransport.Error`, such as `Error.NotFound` or `Error.RateLimited`. Failures of the HTTP exchange are raised as httpx raises them. An answer above 16 MB raises `ResponseTooLarge`.

A client can be built on an httpx client of your own, `Client(http_client=...)`, for example to use a proxy. That client has to set the `User-Agent` itself and must not follow redirects.

An application with its own HTTP stack can skip the clients: `Network.locations_request(query)` returns the request to send, and `Network.parse_locations(response)` reads the answer. Departures and trips have the same pair.

## Known limitations

The model classes are generated by [UniFFI](https://mozilla.github.io/uniffi-rs/), and type checkers stumble over the generated code in two places. Both work at runtime; a typed application needs an ignore comment there.

- `Place.ID("...")`, `Place.COORDINATE(...)` and the `TripTime` variants are rejected where a `Place` or `TripTime` is expected. Each takes its one value as a positional argument.
- pyright rejects `except Error:`. Catching a subclass such as `Error.NotFound` is accepted, and the fields of the subclasses are untyped.

`str()` of an error shows only its fields and is empty for errors without any, such as `Error.RateLimited`. Use `repr()` in messages.

<!-- ANCHOR_END: site -->

## Development

The package is built with [maturin](https://www.maturin.rs) from the crate in `bindings/uniffi`. Inside the repository's nix shell:

```sh
uv sync                                          # build the Rust library, install into .venv
uv sync --reinstall-package publictransport      # again after a change to the Rust code
ruff check . && ruff format --check . && pyright
uv run pytest
```

