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), 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 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.
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 has this guide with a short program for each kind of request, which are also in examples.
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.
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, 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 theTripTimevariants are rejected where aPlaceorTripTimeis expected. Each takes its one value as a positional argument.- pyright rejects
except Error:. Catching a subclass such asError.NotFoundis 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.
Examples
The repository has these as programs to run, in examples.
Search for places by name
"""Search for places by name on the EFA server of VVO in Dresden."""
from publictransport import BundledNetwork, Client
# Servers want to know who asks: name your application and a way to reach you.
USER_AGENT = "publictransport-example (+https://github.com/kiliankoe/publictransport)"
network = BundledNetwork.VVO_EFA.network()
with Client(user_agent=USER_AGENT) as client:
# Every kind of place. `kinds=[LocationKind.STOP]` asks for stops only.
locations = client.locations(network, "Dresden Zwinger")
# The best match comes first.
for location in locations[:5]:
position = ""
if location.coordinate:
latitude, longitude = (
location.coordinate.latitude,
location.coordinate.longitude,
)
position = f" at {latitude:.4f}, {longitude:.4f}"
print(f"{location.kind.name}: {location.name} ({location.id}){position}")
List the next departures at a stop
"""List the next departures at a stop on the HAFAS server of VBB in Berlin."""
from datetime import datetime
from publictransport import BundledNetwork, Client, Location, LocationKind
# Servers want to know who asks: name your application and a way to reach you.
USER_AGENT = "publictransport-example (+https://github.com/kiliankoe/publictransport)"
def local_time(stop: Location, time: datetime) -> str:
"""Give the time of day on the clocks at the stop.
Times are in UTC, and a location knows the time zone to show them in,
where the server names it.
"""
local = stop.local_time(time)
return local.strftime("%H:%M") if local else "??:??"
network = BundledNetwork.VBB_HAFAS.network()
with Client(user_agent=USER_AGENT) as client:
stop = client.locations(network, "S+U Alexanderplatz", kinds=[LocationKind.STOP])[0]
# From now on. `time=` asks for another time.
departures = client.departures(network, stop, limit=10)
print(f"Departures at {stop.name}:")
for departure in departures:
# Only departures with real-time data have a delay.
delay = ""
if departure.realtime_time:
seconds = (departure.realtime_time - departure.scheduled_time).total_seconds()
delay = f"{int(seconds / 60):+d}"
print(
f" {local_time(departure.stop, departure.scheduled_time)} {delay:>3}"
f" {departure.line.name:<5} {departure.direction or '?'}"
f"{' (cancelled)' if departure.cancelled else ''}",
)
Plan trips, and ask for later ones
"""Plan trips between two stops on the OTP server of Entur in Norway.
Then ask for the trips after the first ones.
"""
from publictransport import (
BundledNetwork,
Client,
Header,
LegEnd,
LegKind,
LocationKind,
Trip,
)
# Servers want to know who asks: name your application and a way to reach you.
USER_AGENT = "publictransport-example (+https://github.com/kiliankoe/publictransport)"
def local_time(end: LegEnd) -> str:
"""Give the expected time of day on the clocks at the stop.
That is the real-time one if there is one. Times are in UTC, and a
location knows the time zone to show them in, where the server names it.
"""
local = end.stop.local_time(end.expected_time())
return local.strftime("%H:%M") if local else "??:??"
def print_trip(trip: Trip) -> None:
"""Print a trip and its legs."""
departure, arrival = trip.departure(), trip.arrival()
if not departure or not arrival:
return
times = f"{local_time(departure)} to {local_time(arrival)}"
print(f" {times}, {trip.transfers()} change(s)")
for leg in trip.legs:
if isinstance(leg.kind, LegKind.TRANSIT):
how = f"{leg.kind.line.name} to {leg.kind.direction or '?'}"
elif isinstance(leg.kind, LegKind.WALK):
how = "walk"
else:
how = "other"
print(
f" {local_time(leg.departure)} {leg.departure.stop.name}"
f" -> {local_time(leg.arrival)} {leg.arrival.stop.name}: {how}",
)
network = BundledNetwork.ENTUR.network()
# Entur asks every client for its name, as `company-application`.
network.headers.append(Header(name="ET-Client-Name", value="publictransport-example"))
with Client(user_agent=USER_AGENT) as client:
origin = client.locations(network, "Oslo S", kinds=[LocationKind.STOP])[0]
destination = client.locations(
network, "Lillehammer stasjon", kinds=[LocationKind.STOP]
)[0]
# Leaving now. `depart_at=` and `arrive_by=` ask for another time.
# An end can also be a coordinate or the ID of a stop.
found = client.trips(network, origin, destination, limit=3)
print(f"Trips from {origin.name} to {destination.name}:")
for trip in found.trips:
print_trip(trip)
# The same arguments again, with the reference to the trips after these.
if found.later:
print("Later trips:")
more = client.trips(network, origin, destination, limit=3, page=found.later)
for trip in more.trips:
print_trip(trip)
Find the bundled networks for a position
"""List the bundled networks that cover a position.
This sends no request: the networks and their areas ship with the package.
"""
from publictransport import Coordinate, Registry
registry = Registry.bundled()
print(f"{len(registry.networks())} networks are bundled.")
duesseldorf = Coordinate(latitude=51.2198, longitude=6.7943)
# The best coverage comes first: real-time data, then complete timetables,
# then any data.
print("At Düsseldorf Hauptbahnhof:")
for covering in registry.covering(duesseldorf):
network = covering.network
tier, protocol = covering.tier.name, network.protocol.name
print(f" {tier}: {network.name} ({network.id}, {protocol})")
# A network by its ID, as an application would store it.
network = registry.get("vrr-efa")
if network:
print(f"vrr-efa is {network.name} at {network.endpoint}")