🚉 Public Transport SDK
A client library for public transport APIs, for Rust, Python, Swift, Kotlin and TypeScript. The libraries use a shared model for stops, departures and trips that covers several server types, so an application can query any supported network the same way.
The project is at an early stage. It can search for locations by name, list the departures at a stop and plan trips between two places on servers that speak one of six protocols:
- EFA, the JSON interface of MDV’s journey planner, used by many German transport associations
- MOTIS, the routing engine behind Transitous
- TRIAS 1.2, the German XML standard VDV 431-2
- OJP 1.0, its European successor
- HAFAS mgate, the JSON interface behind the apps of many operators
- OpenTripPlanner 2 with its Transmodel API
The library ships with networks that were checked against their live servers, named by BundledNetwork and listed by Registry::bundled(): VVO, VRR, Transitous, Entur and the HAFAS servers of about 35 operators in Europe and the USA. Further networks can be described in code or read from entries in the format of transport-apis. Each network says where it has coverage, so an application can pick the networks for a position.
Design
The core crate does no I/O. It builds HTTP requests and parses HTTP responses, and the caller sends them. This keeps the core usable from other languages and from WebAssembly, where each platform brings its own HTTP stack. The crate documentation of publictransport shows the request and parse steps and what the HTTP client has to do.
Rust applications that do not want to bring their own HTTP client use publictransport-client, which sends the requests with reqwest. Packages for Python, Swift, Kotlin and TypeScript wrap the same core, each with a client on its platform’s HTTP stack: httpx, URLSession, OkHttp and fetch.
The documentation has a guide for each language, and examples has a short program for each kind of request.
Install
| Language | Package | |
|---|---|---|
| Rust | cargo add publictransport-client, or publictransport alone to bring your own HTTP client | crates/client, crates/core |
| Python | uv add publictransport or pip install publictransport | packages/python |
| Swift | .package(url: "https://github.com/kiliankoe/publictransport", from: "0.1.2"), product PublicTransport | packages/swift |
| Kotlin | implementation("io.github.kiliankoe:publictransport:0.1.2") | packages/kotlin |
| TypeScript | pnpm add @kiliankoe/publictransport or npm install @kiliankoe/publictransport | packages/typescript |
Shared Core
Every language runs the same Rust core, so a request is built and an answer is read the same way everywhere.
- The model is defined once, in Rust. Each language gets the types that UniFFI generates from it. To make things more idiomatic, the generator’s settings and a small script adapt details, such as
scripts/swift-idioms.pyandscripts/kotlin-idioms.py. TypeScript runs the core as WebAssembly and gets its types from wasm-bindgen and tsify, steered by attributes on the Rust types. - Written by hand in each language are the client on the platform’s HTTP stack, and the bridges to the platform’s own types, such as
TimeZonein Swift or the error classes in TypeScript. - A convenience that every language can use goes into the Rust code, not into one package.
publictransport for Rust
Two crates make up the Rust library. publictransport-client sends requests with reqwest and is what most applications want. publictransport is the core that it is built on: it builds HTTP requests and parses HTTP responses without doing I/O, for applications that bring their own HTTP client.
cargo add publictransport-client
The client needs a Tokio runtime. It re-exports the core, so an application depends on the one crate.
use publictransport_client::{BundledNetwork, Client, LocationKind, LocationQuery, Network, TripsQuery};
let client = Client::new("my-app/1.0 (+https://example.org)")?;
let vvo = Network::bundled(BundledNetwork::VvoEfa);
let query = LocationQuery::new("Hauptbahnhof").with_kinds([LocationKind::Stop]);
let stops = client.locations(&vvo, query).await?;
if let [from, to, ..] = stops.as_slice() {
for departure in client.departures(&vvo, from).await? {
// The time on the clocks at the stop, where its time zone is known.
if let Some(time) = departure.stop.local_time(departure.scheduled_time) {
println!("{time} {} to {:?}", departure.line.name, departure.direction);
}
}
let found = client.trips(&vvo, TripsQuery::new(from, to)).await?;
}
Network::bundled gives a network that ships with the crate by name. Registry::bundled() holds them all: get("vvo-efa") finds one by its ID as text, and covering(coordinate) lists the networks for a position. A Network can also be described in code with Network::new, or read from an entry in the format of transport-apis with Network::from_json.
A stop or a place in a query is a Location from a search, a departure or a trip, or an ID as text; a place in a trips query can be a Coordinate too. A location that another network returned works as well.
Times are Timestamp values in UTC. Location::local_time gives one as the clocks at that location show it, or None where no time zone is known for it.
An answer to a trips query has the list in trips, and earlier and later are references for more: pass one to TripsQuery::with_page on the same query. The limit of a query is not a maximum, servers treat it as a guide.
The client does not retry, limit its request rate or cache, and it does not follow redirects. Its Error tells a failed HTTP exchange from what the server or the query got wrong.
The API documentation on docs.rs has the details: publictransport-client for the client and its features, and publictransport for the model and for the request and parse steps an own HTTP client needs.
Examples
The repository has these as programs to run, in examples.
Search for places by name
//! Searches for places by name on the EFA server of VVO, the transport
//! association of Dresden.
use publictransport_client::{BundledNetwork, Client, LocationQuery, Network};
// Servers want to know who asks: name your application and a way to reach you.
const USER_AGENT: &str = "publictransport-example (+https://github.com/kiliankoe/publictransport)";
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let network = Network::bundled(BundledNetwork::VvoEfa);
let client = Client::new(USER_AGENT)?;
// Every kind of place. `with_kinds([LocationKind::Stop])` asks for stops only.
let query = LocationQuery::new("Dresden Zwinger");
let locations = client.locations(&network, &query).await?;
// The best match comes first.
for location in locations.iter().take(5) {
let position = location.coordinate.map_or_else(String::new, |coordinate| {
format!(
" at {:.4}, {:.4}",
coordinate.latitude, coordinate.longitude
)
});
println!(
"{:?}: {} ({}){position}",
location.kind, location.name, location.id
);
}
Ok(())
}
List the next departures at a stop
//! Lists the next departures at a stop on the HAFAS server of VBB, the
//! transport association of Berlin and Brandenburg.
use publictransport_client::{
BundledNetwork, Client, DeparturesQuery, Location, LocationKind, LocationQuery, Network,
Timestamp,
};
// Servers want to know who asks: name your application and a way to reach you.
const USER_AGENT: &str = "publictransport-example (+https://github.com/kiliankoe/publictransport)";
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let network = Network::bundled(BundledNetwork::VbbHafas);
let client = Client::new(USER_AGENT)?;
let query = LocationQuery::new("S+U Alexanderplatz").with_kinds([LocationKind::Stop]);
let stops = client.locations(&network, &query).await?;
let stop = stops.first().ok_or("found no stop")?;
// From now on. `with_time` asks for another time.
let query = DeparturesQuery::new(stop).with_limit(10);
println!("Departures at {}:", stop.name);
for departure in client.departures(&network, &query).await? {
// Only departures with real-time data have a delay.
let delay = departure.realtime_time.map_or_else(String::new, |time| {
let seconds = time.unix_seconds - departure.scheduled_time.unix_seconds;
format!("{:+}", seconds / 60)
});
println!(
" {} {delay:>3} {:<5} {}{}",
local_time(&departure.stop, departure.scheduled_time),
departure.line.name,
departure.direction.as_deref().unwrap_or("?"),
if departure.cancelled {
" (cancelled)"
} else {
""
},
);
}
Ok(())
}
/// 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.
fn local_time(stop: &Location, time: Timestamp) -> String {
stop.local_time(time)
.map_or_else(|| "??:??".to_owned(), |time| time.to_string())
}
Plan trips, and ask for later ones
//! Plans trips between two stops on the OTP server of Entur, the journey
//! planner for Norway, and asks for the trips after the first ones.
use publictransport_client::{
BundledNetwork, Client, LegEnd, LegKind, Location, LocationKind, LocationQuery, Network, Trip,
TripsQuery,
};
// Servers want to know who asks: name your application and a way to reach you.
const USER_AGENT: &str = "publictransport-example (+https://github.com/kiliankoe/publictransport)";
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Entur asks every client for its name, as `company-application`.
let network = Network::bundled(BundledNetwork::Entur)
.with_header("ET-Client-Name", "publictransport-example");
let client = Client::new(USER_AGENT)?;
let from = first_stop(&client, &network, "Oslo S").await?;
let to = first_stop(&client, &network, "Lillehammer stasjon").await?;
// Leaving now. `with_departure` and `with_arrival` ask for another time.
// An end can also be a coordinate or the ID of a stop.
let query = TripsQuery::new(&from, &to).with_limit(3);
let found = client.trips(&network, &query).await?;
println!("Trips from {} to {}:", from.name, to.name);
found.trips.iter().for_each(print_trip);
// The same query again, with the reference to the trips after these.
if let Some(later) = found.later {
println!("Later trips:");
let more = client.trips(&network, &query.with_page(later)).await?;
more.trips.iter().for_each(print_trip);
}
Ok(())
}
async fn first_stop(
client: &Client,
network: &Network,
text: &str,
) -> Result<Location, Box<dyn std::error::Error>> {
let query = LocationQuery::new(text).with_kinds([LocationKind::Stop]);
let stops = client.locations(network, &query).await?;
stops
.into_iter()
.next()
.ok_or_else(|| format!("found no stop for {text}").into())
}
fn print_trip(trip: &Trip) {
let (Some(departure), Some(arrival)) = (trip.departure(), trip.arrival()) else {
return;
};
println!(
" {} to {}, {} change(s)",
local_time(departure),
local_time(arrival),
trip.transfers()
);
for leg in &trip.legs {
let how = match &leg.kind {
LegKind::Transit { line, direction } => {
format!("{} to {}", line.name, direction.as_deref().unwrap_or("?"))
}
LegKind::Walk => "walk".to_owned(),
_ => "other".to_owned(),
};
println!(
" {} {} -> {} {}: {how}",
local_time(&leg.departure),
leg.departure.stop.name,
local_time(&leg.arrival),
leg.arrival.stop.name,
);
}
}
/// The expected time of day on the clocks at the stop: 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.
fn local_time(end: &LegEnd) -> String {
end.stop
.local_time(end.expected_time())
.map_or_else(|| "??:??".to_owned(), |time| time.to_string())
}
Find the bundled networks for a position
//! Lists the bundled networks that cover a position. This sends no
//! request: the networks and their areas ship with the library.
use publictransport_client::{Coordinate, Registry};
fn main() {
let registry = Registry::bundled();
println!("{} networks are bundled.", registry.networks().len());
let duesseldorf = Coordinate {
latitude: 51.2198,
longitude: 6.7943,
};
// The best coverage comes first: real-time data, then complete
// timetables, then any data.
println!("At Düsseldorf Hauptbahnhof:");
for covering in registry.covering(duesseldorf) {
let network = covering.network;
println!(
" {:?}: {} ({}, {:?})",
covering.tier, network.name, network.id, network.protocol
);
}
// A network by its ID, as an application would store it.
if let Some(network) = registry.get("vrr-efa") {
println!("vrr-efa is {} at {}", network.name, network.endpoint);
}
}
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}")
PublicTransport for Swift
A Swift 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 URLSession sends them. It runs on iOS, macOS, tvOS, watchOS and visionOS from version 26, and on Linux.
Add it to a project by the URL of this repository, and depend on a version:
.package(url: "https://github.com/kiliankoe/publictransport", from: "0.1.2")
On Apple platforms the package downloads the Rust library as a binary from the release. Between releases the code on a branch can be ahead of that binary, so a dependency on a branch does not work. On Linux the package links the library from a directory you name, see “Development”. On watchOS the library covers only the watches with a 64-bit processor (Series 9 and later), so an app for all watches does not link yet.
import PublicTransport
let client = Client(userAgent: "my-app/1.0 (+https://example.org)")
let network = Network.bundled(.vvoEfa)
let stops = try await client.locations(in: network, matching: "Hauptbahnhof", kinds: [.stop])
guard let from = stops.first, let to = stops.dropFirst().first else { return }
for departure in try await client.departures(in: network, at: from, limit: 10) {
print(departure.scheduledTime, departure.line.name, departure.direction ?? "")
}
let found = try await client.trips(in: network, from: from, to: to, limit: 5)
// The same arguments again, with the reference to the trips after these.
let more = try await client.trips(in: network, from: from, to: to, limit: 5, page: found.later)
The documentation has this guide with a short program for each kind of request, which are also in examples.
Network.bundled(_:) gives a network that ships with the package by name. Registry.bundled() holds them all, for a list to choose from: network(id:) finds one by its ID as text, and covering(at:) lists the networks for a position. A Network can also be described in code or read from an entry in the format of transport-apis with Network(id:json:).
A stop or a place is a Location from a search, a departure or a trip, or a String with an ID; a place in trips can be a Coordinate too, or a CLLocationCoordinate2D where Core Location exists. 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 call also takes a query of the Rust library (LocationQuery, DeparturesQuery, TripsQuery) with the label query:.
Times are Date values. Location.timeZone is the time zone to show them in.
Location and Network are Identifiable. A Departure and a Trip have no identifier from the server; they are Hashable, so a list can use id: \.self.
What a query takes and what an answer holds is Codable: Location, Departure, Trip, the queries and the types inside them. An enum without values is stored as the name of its case, and a BundledNetwork as the ID of its network. An enum with values has the form that Swift writes for it, such as {"id": {"_0": "de:14612:28"}} for Place.id, and a Date the form that the encoder is set to. A Network is not Codable, because it can hold credentials and has a JSON form of its own; store its ID and find it again with Registry.bundled().network(id:).
The stored form follows the model, so it can change where the model does: with any minor version before 1.0, and with a major version after. Read stored values with try? and fetch them again when that fails. For what has to outlive an update, such as a favorite stop, store network.id and location.id.
Failures that the server or the query cause are thrown as PublicTransportError, such as .notFound or .rateLimited; its localizedDescription is a sentence in English. Failures of the HTTP exchange are thrown as URLError, and a cancelled task throws CancellationError. An answer above 16 MB is ClientError.responseTooLarge. The client does not follow redirects: a moved server is PublicTransportError.moved. It does not retry, limit its request rate or cache.
Some networks need more than their entry holds. Entur asks every client for its name in the header ET-Client-Name (company-application): add it to network.headers. An answer to trips from an OpenTripPlanner server can be empty at night and still have a later reference to follow.
Examples
The repository has these as programs to run, in examples.
Search for places by name
// Searches for places by name on the EFA server of VVO, the transport
// association of Dresden.
import Foundation
import PublicTransport
// Servers want to know who asks: name your application and a way to reach you.
let client = Client(userAgent: "publictransport-example (+https://github.com/kiliankoe/publictransport)")
let network = Network.bundled(.vvoEfa)
// Every kind of place. `kinds: [.stop]` asks for stops only.
let locations = try await client.locations(in: network, matching: "Dresden Zwinger")
// The best match comes first.
for location in locations.prefix(5) {
var position = ""
if let coordinate = location.coordinate {
position = String(format: " at %.4f, %.4f", coordinate.latitude, coordinate.longitude)
}
print("\(location.kind): \(location.name) (\(location.id))\(position)")
}
List the next departures at a stop
// Lists the next departures at a stop on the HAFAS server of VBB, the
// transport association of Berlin and Brandenburg.
import Foundation
import PublicTransport
// Servers want to know who asks: name your application and a way to reach you.
let client = Client(userAgent: "publictransport-example (+https://github.com/kiliankoe/publictransport)")
let network = Network.bundled(.vbbHafas)
let stops = try await client.locations(in: network, matching: "S+U Alexanderplatz", kinds: [.stop])
guard let stop = stops.first else { fatalError("found no stop") }
/// The time of day at the stop. Times are `Date` values, and a location
/// has the time zone to show them in.
func localTime(at stop: Location, _ time: Date) -> String {
time.formatted(Date.FormatStyle(time: .shortened, timeZone: stop.timeZone ?? .gmt))
}
print("Departures at \(stop.name):")
// From now on. `after:` asks for another time.
for departure in try await client.departures(in: network, at: stop, limit: 10) {
// Only departures with real-time data have a delay.
var delay = ""
if let realtime = departure.realtimeTime {
let minutes = Int(realtime.timeIntervalSince(departure.scheduledTime) / 60)
delay = minutes < 0 ? "\(minutes)" : "+\(minutes)"
}
print(
" \(localTime(at: departure.stop, departure.scheduledTime)) \(delay)"
+ " \(departure.line.name) \(departure.direction ?? "?")"
+ (departure.cancelled ? " (cancelled)" : ""))
}
Plan trips, and ask for later ones
// Plans trips between two stops on the OTP server of Entur, the journey
// planner for Norway, and asks for the trips after the first ones.
import Foundation
import PublicTransport
// Servers want to know who asks: name your application and a way to reach you.
let client = Client(userAgent: "publictransport-example (+https://github.com/kiliankoe/publictransport)")
var network = Network.bundled(.entur)
// Entur asks every client for its name, as `company-application`.
network.headers.append(Header(name: "ET-Client-Name", value: "publictransport-example"))
/// The expected time of day at the stop: the real-time one if there is
/// one. Times are `Date` values, and a location has the time zone to show
/// them in.
func localTime(_ end: LegEnd) -> String {
end.expectedTime.formatted(Date.FormatStyle(time: .shortened, timeZone: end.stop.timeZone ?? .gmt))
}
func printTrip(_ trip: Trip) {
guard let departure = trip.departure, let arrival = trip.arrival else { return }
print(" \(localTime(departure)) to \(localTime(arrival)), \(trip.transfers) change(s)")
for leg in trip.legs {
let how =
switch leg.kind {
case .transit(let line, let direction): "\(line.name) to \(direction ?? "?")"
case .walk: "walk"
default: "other"
}
print(
" \(localTime(leg.departure)) \(leg.departure.stop.name)"
+ " -> \(localTime(leg.arrival)) \(leg.arrival.stop.name): \(how)")
}
}
let origins = try await client.locations(in: network, matching: "Oslo S", kinds: [.stop])
let destinations = try await client.locations(in: network, matching: "Lillehammer stasjon", kinds: [.stop])
guard let origin = origins.first, let destination = destinations.first else { fatalError("found no stop") }
// Leaving now. `departingAt:` and `arrivingBy:` ask for another time.
// An end can also be a coordinate or the ID of a stop.
let found = try await client.trips(in: network, from: origin, to: destination, limit: 3)
print("Trips from \(origin.name) to \(destination.name):")
found.trips.forEach(printTrip)
// The same arguments again, with the reference to the trips after these.
if let later = found.later {
print("Later trips:")
let more = try await client.trips(in: network, from: origin, to: destination, limit: 3, page: later)
more.trips.forEach(printTrip)
}
Find the bundled networks for a position
// Lists the bundled networks that cover a position. This sends no request:
// the networks and their areas ship with the package.
import PublicTransport
let registry = Registry.bundled()
print("\(registry.networks().count) networks are bundled.")
let 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(at: duesseldorf) {
let network = covering.network
print(" \(covering.tier): \(network.name) (\(network.id), \(network.protocol))")
}
// A network by its ID, as an application would store it.
if let network = registry.network(id: "vrr-efa") {
print("vrr-efa is \(network.name) at \(network.endpoint)")
}
publictransport for Kotlin
A Kotlin 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 OkHttp sends them from suspend functions. It runs on the JVM from Java 11.
The package is on Maven Central, for macOS and Linux (with glibc, so not Alpine) on x86-64 and ARM and for Windows on x86-64. An Android library is planned.
dependencies {
implementation("io.github.kiliankoe:publictransport:0.1.2")
}
import publictransport.BundledNetwork
import publictransport.Client
import publictransport.LocationKind
val client = Client("my-app/1.0 (+https://example.org)")
val network = BundledNetwork.VVO_EFA.network()
val stops = client.locations(network, "Hauptbahnhof", kinds = listOf(LocationKind.STOP))
val (from, to) = stops
for (departure in client.departures(network, from, limit = 10)) {
// The time on the clocks at the stop, where its time zone is known.
val time = departure.stop.localTime(departure.scheduledTime)
println("${time?.toLocalTime() ?: "?"} ${departure.line.name} ${departure.direction ?: ""}")
}
val found = client.trips(network, from, to, limit = 5)
// The same arguments again, with the reference to the trips after these.
val more = client.trips(network, from, to, limit = 5, page = found.later)
The examples have a short program for each kind of request.
BundledNetwork names the networks that ship with the package, and network() gives one. 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 networkFromJson(id, json) reads further ones from entries in the format of transport-apis.
The model types are data classes with val properties, so copy makes a changed one: network.copy(headers = network.headers + Header("X-Api-Key", key)).
departures takes a Location from a search, a departure or a trip, or the ID of a stop as a String. trips takes two locations, or two Place values for other ends: asPlace() makes one from a location or a Coordinate, as in client.trips(network, stop.asPlace(), Coordinate(51.04, 13.73).asPlace()), and Place.Id names a stop by its ID on the network that is asked. 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 call also takes a query of the Rust library (LocationQuery, DeparturesQuery, TripsQuery) in place of the plain values.
Times are java.time.Instant values. Location.localTime(time) gives one as the clocks at that location show it, an OffsetDateTime with the offset that holds there at that time, or null where no time zone is known for it. An EFA network needs its timezone to send a query time. A TRIAS or OJP network needs a requestorRef, which public servers document, e.g. OpenService. A HAFAS network needs hafas = HafasOptions(...) and its timezone; the bundled ones have both.
trips returns a Trips value: 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. An answer from an OpenTripPlanner server can be empty at night and still have a later reference to follow.
Failures that the server or the query cause are thrown as subclasses of PublicTransportException, such as PublicTransportException.NotFound or PublicTransportException.RateLimited; its message is a sentence in English. Failures of the HTTP exchange are thrown as OkHttp throws them, as an IOException. An answer above 16 MB is a ResponseTooLargeException, which is an IOException too. A cancelled coroutine cancels its request. The client does not follow redirects: a moved server is PublicTransportException.Moved. It does not retry, limit its request rate or cache.
One client serves every network, so create one and keep it. It can be built on an OkHttpClient of your own, Client(userAgent, httpClient), for example to use a proxy or an interceptor. The client uses its connections and settings, except that it never follows a redirect and never sends a request again.
Some networks need more than their entry holds. Entur asks every client for its name in the header ET-Client-Name (company-application) and limits clients without it: add it to the headers of the bundled network with copy, as above.
An application with its own HTTP stack can skip the client: Network.locationsRequest(query) returns the request to send, and Network.parseLocations(response) reads the answer. Departures and trips have the same pair.
Known limitations
The model classes are generated by UniFFI, which shows in a few places.
- The value of a
Placeor aTripTimecase is namedv1, as inPlace.Id("de:14612:28").v1. toString()of a model value is the debug text of the Rust library, with Rust’s names for the fields. It leaves out the values of headers, which can be credentials.- The package
publictransportalso has the helpers of the generated code, such asFfiConverterString. They are no part of the API. - The documentation of the model types comes from the Rust code, so it links and names things as Rust does:
[`Location::local_time`]isLocation.localTime,Noneisnull, andErrorisPublicTransportException. - A
RegistryisAutoCloseable, because it lives in the Rust library. Closing it is optional: its memory is freed when the object is collected. - The Rust library is loaded with JNA. From Java 24 on, the JVM prints a warning about that unless it is started with
--enable-native-access=ALL-UNNAMED.
Examples
The repository has these as programs to run, in examples.
Search for places by name
// Searches for places by name on the EFA server of VVO, the transport
// association of Dresden.
import publictransport.BundledNetwork
import publictransport.Client
import java.util.Locale
suspend fun main() {
// Servers want to know who asks: name your application and a way to reach you.
val client = Client("publictransport-example (+https://github.com/kiliankoe/publictransport)")
val network = BundledNetwork.VVO_EFA.network()
// Every kind of place. `kinds = listOf(LocationKind.STOP)` asks for stops only.
val locations = client.locations(network, "Dresden Zwinger")
// The best match comes first.
for (location in locations.take(5)) {
val position =
location.coordinate?.let { " at %.4f, %.4f".format(Locale.ROOT, it.latitude, it.longitude) } ?: ""
println("${location.kind}: ${location.name} (${location.id})$position")
}
}
List the next departures at a stop
// Lists the next departures at a stop on the HAFAS server of VBB, the
// transport association of Berlin and Brandenburg.
import publictransport.BundledNetwork
import publictransport.Client
import publictransport.LocationKind
import java.time.Duration
import java.time.format.DateTimeFormatter
private val clock = DateTimeFormatter.ofPattern("HH:mm")
suspend fun main() {
// Servers want to know who asks: name your application and a way to reach you.
val client = Client("publictransport-example (+https://github.com/kiliankoe/publictransport)")
val network = BundledNetwork.VBB_HAFAS.network()
val stop = client.locations(network, "S+U Alexanderplatz", kinds = listOf(LocationKind.STOP)).first()
println("Departures at ${stop.name}:")
// From now on. `time =` asks for another time.
for (departure in client.departures(network, stop, limit = 10)) {
// Times are `Instant` values, and a location gives the time on the
// clocks there, where the server names its time zone.
val time = departure.stop.localTime(departure.scheduledTime)?.format(clock) ?: "??:??"
// Only departures with real-time data have a delay.
val delay =
departure.realtimeTime?.let { "%+d".format(Duration.between(departure.scheduledTime, it).toMinutes()) }
println(
" $time ${(delay ?: "").padStart(3)} ${departure.line.name.padEnd(5)} ${departure.direction ?: "?"}" +
if (departure.cancelled) " (cancelled)" else "",
)
}
}
Plan trips, and ask for later ones
// Plans trips between two stops on the OTP server of Entur, the journey
// planner for Norway, and asks for the trips after the first ones.
import publictransport.BundledNetwork
import publictransport.Client
import publictransport.Header
import publictransport.LegEnd
import publictransport.LegKind
import publictransport.LocationKind
import publictransport.Trip
import java.time.format.DateTimeFormatter
private val clock = DateTimeFormatter.ofPattern("HH:mm")
// The expected time of day at the stop: the real-time one if there is one.
// Times are `Instant` values, and a location gives the time on the clocks
// there, where the server names its time zone.
private fun localTime(end: LegEnd): String = end.stop.localTime(end.expectedTime)?.format(clock) ?: "??:??"
private fun printTrip(trip: Trip) {
val departure = trip.departure ?: return
val arrival = trip.arrival ?: return
println(" ${localTime(departure)} to ${localTime(arrival)}, ${trip.transfers} change(s)")
for (leg in trip.legs) {
val how =
when (val kind = leg.kind) {
is LegKind.Transit -> "${kind.line.name} to ${kind.direction ?: "?"}"
is LegKind.Walk -> "walk"
else -> "other"
}
println(
" ${localTime(leg.departure)} ${leg.departure.stop.name}" +
" -> ${localTime(leg.arrival)} ${leg.arrival.stop.name}: $how",
)
}
}
suspend fun main() {
// Servers want to know who asks: name your application and a way to reach you.
val client = Client("publictransport-example (+https://github.com/kiliankoe/publictransport)")
val entur = BundledNetwork.ENTUR.network()
// Entur asks every client for its name, as `company-application`.
val network = entur.copy(headers = entur.headers + Header("ET-Client-Name", "publictransport-example"))
val origin = client.locations(network, "Oslo S", kinds = listOf(LocationKind.STOP)).first()
val destination = client.locations(network, "Lillehammer stasjon", kinds = listOf(LocationKind.STOP)).first()
// Leaving now. `departAt =` and `arriveBy =` ask for another time.
// An end can also be a coordinate, with `asPlace()` on both ends, or the
// ID of a stop as a `Place.Id`.
val found = client.trips(network, origin, destination, limit = 3)
println("Trips from ${origin.name} to ${destination.name}:")
found.trips.forEach(::printTrip)
// The same arguments again, with the reference to the trips after these.
found.later?.let { later ->
println("Later trips:")
val more = client.trips(network, origin, destination, limit = 3, page = later)
more.trips.forEach(::printTrip)
}
}
Find the bundled networks for a position
// Lists the bundled networks that cover a position. This sends no request:
// the networks and their areas ship with the package.
import publictransport.Coordinate
import publictransport.Registry
fun main() {
val registry = Registry.bundled()
println("${registry.networks().size} networks are bundled.")
val duesseldorf = Coordinate(latitude = 51.2198, longitude = 6.7943)
// The best coverage comes first: real-time data, then complete timetables,
// then any data.
println("At Düsseldorf Hauptbahnhof:")
for (covering in registry.covering(duesseldorf)) {
val network = covering.network
println(" ${covering.tier}: ${network.name} (${network.id}, ${network.protocol})")
}
// A network by its ID, as an application would store it.
registry.get("vrr-efa")?.let { network ->
println("vrr-efa is ${network.name} at ${network.endpoint}")
}
}
publictransport for TypeScript
A TypeScript and JavaScript 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, compiled to WebAssembly. The Rust code builds the requests and parses the answers, and fetch sends them. It runs on Node.js from version 22, on Deno and on Bun. It has no dependencies and is an ES module only. The WebAssembly code is part of the JavaScript, so no runtime or bundler needs any setup to load it.
In a browser the package loads and works, but a page can reach few servers directly: most transport servers do not allow requests from other origins (CORS), and a browser may not let a script set the User-Agent that some servers require. A page therefore needs a proxy that it controls, see fetch below.
The package is on npm as @kiliankoe/publictransport:
pnpm add @kiliankoe/publictransport
import { bundledNetwork, Client } from "@kiliankoe/publictransport";
const client = new Client("my-app/1.0 (+https://example.org)");
const network = bundledNetwork("vvo-efa");
const [from, to] = await client.locations(network, "Hauptbahnhof", { kinds: ["stop"] });
if (!(from && to)) throw new Error("no stops found");
for (const departure of await client.departures(network, from, { limit: 10 })) {
// The time on the clocks at the stop. Without a time zone it would be the one of this machine.
const time = departure.scheduledTime.toLocaleTimeString("en-GB", {
timeZone: departure.stop.timezone,
timeStyle: "short",
});
console.log(`${time} ${departure.line.name} ${departure.direction ?? ""}`);
}
const found = await client.trips(network, from, to, { limit: 5 });
// The same arguments again, with the reference to the trips after these.
const more = await client.trips(network, from, to, { limit: 5, page: found.later });
The examples have a short program for each kind of request.
bundledNetwork("vvo-efa") gives one of the networks that ship with the package; the type BundledNetwork lists their IDs. Registry.bundled() holds them all, for a list to choose from: get("vvo-efa") finds one by an ID that is only known at run time, and covering({ latitude, longitude }) lists the networks for a position, each with the tier of its coverage there. A Network can also be written by hand, as { id: ..., name: ..., endpoint: ..., protocol: "efa", timezone: "Europe/Berlin" }, and networkFromJson(id, json) reads further ones from entries in the format of transport-apis.
The model types are plain objects, described by interfaces, so a spread makes a changed one: { ...network, headers: [...(network.headers ?? []), { name: "X-Api-Key", value: key }] }. A value that the server did not send is a missing key, not null, and a key that is undefined counts as missing where a value is passed in. Enumerations are strings, such as "stop" or "highSpeedTrain", and the kind of a leg is told apart by leg.kind.type. What the other languages have as methods are functions here: localTime(location, time), expectedTime(departure), departure(trip), arrival(trip), transfers(trip), stationIds(location), sameStation(location, other), stopId(network, location), place(network, location) and tierAt(coverage, position).
A place is a Location from a search, a departure or a trip, the ID of a stop on the network that is asked as a string, or a coordinate as { latitude, longitude }. departures takes a location or an ID, trips any two places. 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. The options after the places are the other fields of the query, and for a trip departAt or arriveBy as its time: client.trips(network, from, to, { arriveBy: date, limit: 3 }). Each call also takes the whole query as one object (LocationQuery, DeparturesQuery, TripsQuery), as in client.departures(network, { stop, limit: 10 }). A limit is a guide for the server and not a maximum.
Times are Date values. A location has the name of its time zone as timezone, where the server tells it, so Intl and toLocaleTimeString show a time as the clocks there do, as above. localTime(location, time) gives that time as text in ISO 8601 format with the offset that holds there at that time, such as 2026-11-19T14:08:00+01:00, or undefined where no time zone is known for it. It is text because JavaScript has no type for a time with an offset; Temporal.ZonedDateTime can be made from it where that exists. An EFA network needs its timezone to send a query time. A TRIAS or OJP network needs a requestorRef, which public servers document, e.g. OpenService. A HAFAS network needs hafas and its timezone; the bundled ones have both.
trips returns a Trips value: 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. An answer from an OpenTripPlanner server can be empty at night and still have a later reference to follow.
Failures that the server or the query cause are thrown as subclasses of PublicTransportError, such as NotFoundError or RateLimitedError; the message is a sentence in English, and detail has what the server said where there is more to tell. Failures of the HTTP exchange are thrown as fetch throws them, usually as a TypeError. An answer above 16 MB is a ResponseTooLargeError. The error of a status that is no success says what it means, whatever the body holds: a redirect is a MovedError, 401 an UnauthorizedError, 403 a BlockedError, 429 a RateLimitedError, a status from 500 an UnavailableError, and any other a ServerError with the status. A NotFoundError is a stop or a place that the server does not know, not the status 404. A network or a query of the wrong shape, such as a negative limit, is a TypeError before a request is sent. The client does not retry, limit its request rate or cache, and it sets no time limit. Every call takes a signal among its options, which cancels the request: client.departures(network, stop, { signal: AbortSignal.timeout(30_000) }). A cancelled or timed-out request rejects with the DOMException of the signal, an AbortError or a TimeoutError.
One client serves every network, so create one and keep it. It can be built on a fetch of your own, new Client(userAgent, { fetch }), for example to send the requests through a proxy. A page in a browser needs that for most servers: the function gets the URL of the transport server and the request to send, passes both to a proxy on the page’s own origin, and returns its answer. It has to pass on redirect: "manual" and the signal, and the proxy must not follow redirects either.
Some networks need more than their entry holds. Entur asks every client for its name in the header ET-Client-Name (company-application) and limits clients without it: add it to the headers of the bundled network with a spread, as above.
An application with its own HTTP stack can skip the client: locationsRequest(network, query) returns the request to send, and parseLocations(network, response) reads the answer. Departures and trips have the same pair. The headers of both are lists of { name, value }, since a name can repeat: new Headers(request.headers.map(({ name, value }) => [name, value])) makes those of a fetch.
Known limitations
The model types and the functions on them are generated from the Rust code by wasm-bindgen and tsify, which shows in a few places.
- The documentation of the model types comes from the Rust code, so it links and names things as Rust does:
[`Location::local_time`]islocalTime,scheduled_timeisscheduledTime,Noneis a missing key, andErrorisPublicTransportError. - A network crosses into the WebAssembly module with every call. For one with large coverage areas, such as Transitous, that takes one to two milliseconds.
- The fields that have a default, such as the
headersof aNetworkor theglobalIdsof aLocation, are optional in their types, so that a value written by hand can leave them out. A value from the package always has them. - A
Registrylives in the WebAssembly module. Its memory is freed when the object is collected, or at once withfree(). Its type namesSymbol.dispose, so a project that checks the types of its dependencies (skipLibCheck: false) needsESNext.Disposableinlib, or the types of Node.js. - A page with a Content Security Policy has to allow WebAssembly with
'wasm-unsafe-eval'. - The types
ThrownandFailuredescribe what the WebAssembly module throws. The package turns that into aPublicTransportError, so they are no part of the API.
Examples
The repository has these as programs to run, in examples.
Search for places by name
// Searches for places by name on the EFA server of VVO, the transport
// association of Dresden.
import { bundledNetwork, Client } from "@kiliankoe/publictransport";
// Servers want to know who asks: name your application and a way to reach you.
const client = new Client(
"publictransport-example (+https://github.com/kiliankoe/publictransport)",
);
const network = bundledNetwork("vvo-efa");
// Every kind of place. `{ kinds: ["stop"] }` as a third argument asks for stops only.
const locations = await client.locations(network, "Dresden Zwinger");
// The best match comes first.
for (const location of locations.slice(0, 5)) {
const { coordinate } = location;
const position = coordinate
? ` at ${coordinate.latitude.toFixed(4)}, ${coordinate.longitude.toFixed(4)}`
: "";
console.log(`${location.kind}: ${location.name} (${location.id})${position}`);
}
List the next departures at a stop
// Lists the next departures at a stop on the HAFAS server of VBB, the
// transport association of Berlin and Brandenburg.
import { bundledNetwork, Client } from "@kiliankoe/publictransport";
// Servers want to know who asks: name your application and a way to reach you.
const client = new Client(
"publictransport-example (+https://github.com/kiliankoe/publictransport)",
);
const network = bundledNetwork("vbb-hafas");
const [stop] = await client.locations(network, "S+U Alexanderplatz", { kinds: ["stop"] });
if (!stop) {
throw new Error("the stop was not found");
}
console.log(`Departures at ${stop.name}:`);
// From now on. `time` next to the limit asks for another time.
for (const departure of await client.departures(network, stop, { limit: 10 })) {
// Times are `Date` values. With the time zone of the stop, where the
// server names it, one reads as on the clocks there.
const { timezone } = departure.stop;
const time = timezone
? departure.scheduledTime.toLocaleTimeString("en-GB", {
timeZone: timezone,
timeStyle: "short",
})
: "??:??";
// Only departures with real-time data have a delay.
const late = departure.realtimeTime
? Math.trunc((departure.realtimeTime.getTime() - departure.scheduledTime.getTime()) / 60_000)
: undefined;
const delay = late === undefined ? "" : `${late < 0 ? "" : "+"}${late}`;
console.log(
` ${time} ${delay.padStart(3)} ${departure.line.name.padEnd(5)} ${departure.direction ?? "?"}${
departure.cancelled ? " (cancelled)" : ""
}`,
);
}
Plan trips, and ask for later ones
// Plans trips between two stops on the OTP server of Entur, the journey
// planner for Norway, and asks for the trips after the first ones.
import {
arrival,
bundledNetwork,
Client,
departure,
expectedTime,
type LegEnd,
type Trip,
transfers,
} from "@kiliankoe/publictransport";
// The expected time of day at the stop: the real-time one if there is one.
// Times are `Date` values. With the time zone of the stop, where the server
// names it, one reads as on the clocks there.
function clock(end: LegEnd): string {
const { timezone } = end.stop;
return timezone
? expectedTime(end).toLocaleTimeString("en-GB", { timeZone: timezone, timeStyle: "short" })
: "??:??";
}
function printTrip(trip: Trip) {
const start = departure(trip);
const end = arrival(trip);
if (!(start && end)) {
return;
}
console.log(` ${clock(start)} to ${clock(end)}, ${transfers(trip)} change(s)`);
for (const leg of trip.legs) {
const how =
leg.kind.type === "transit"
? `${leg.kind.line.name} to ${leg.kind.direction ?? "?"}`
: leg.kind.type;
console.log(
` ${clock(leg.departure)} ${leg.departure.stop.name}` +
` -> ${clock(leg.arrival)} ${leg.arrival.stop.name}: ${how}`,
);
}
}
// Servers want to know who asks: name your application and a way to reach you.
const client = new Client(
"publictransport-example (+https://github.com/kiliankoe/publictransport)",
);
const entur = bundledNetwork("entur");
// Entur asks every client for its name, as `company-application`.
const network = {
...entur,
headers: [...(entur.headers ?? []), { name: "ET-Client-Name", value: "publictransport-example" }],
};
const [origin] = await client.locations(network, "Oslo S", { kinds: ["stop"] });
const [destination] = await client.locations(network, "Lillehammer stasjon", { kinds: ["stop"] });
if (!(origin && destination)) {
throw new Error("a stop was not found");
}
// Leaving now. `departAt` or `arriveBy` next to the limit asks for another
// time. An end can also be a coordinate,
// `{ latitude: ..., longitude: ... }`, or the ID of a stop as a string.
const found = await client.trips(network, origin, destination, { limit: 3 });
console.log(`Trips from ${origin.name} to ${destination.name}:`);
found.trips.forEach(printTrip);
// The same arguments again, with the reference to the trips after these.
if (found.later) {
console.log("Later trips:");
const more = await client.trips(network, origin, destination, { limit: 3, page: found.later });
more.trips.forEach(printTrip);
}
Find the bundled networks for a position
// Lists the bundled networks that cover a position. This sends no request:
// the networks and their areas ship with the package.
import { Registry } from "@kiliankoe/publictransport";
const registry = Registry.bundled();
console.log(`${registry.networks().length} networks are bundled.`);
const duesseldorf = { latitude: 51.2198, longitude: 6.7943 };
// The best coverage comes first: real-time data, then complete timetables,
// then any data.
console.log("At Düsseldorf Hauptbahnhof:");
for (const { network, tier } of registry.covering(duesseldorf)) {
console.log(` ${tier}: ${network.name} (${network.id}, ${network.protocol})`);
}
// A network by its ID, as an application would store it.
const network = registry.get("vrr-efa");
if (network) {
console.log(`vrr-efa is ${network.name} at ${network.endpoint}`);
}
Bundled networks
These networks ship with the library. Each was checked against its live server. The ID finds a network in the registry, and BundledNetwork has a name for each, spelled like the ID.
| Network | ID | Protocol | Notes |
|---|---|---|---|
| Verkehrsverbund Oberelbe (VVO) | vvo-efa | EFA | |
| Verkehrsverbund Oberelbe (VVO) | vvo-trias | TRIAS 1.2 | |
| Verkehrsverbund Oberelbe (VVO) | vvo-ojp | OJP 1.0 | no departures |
| Verkehrsverbund Rhein-Ruhr (VRR) | vrr-efa | EFA | |
| Verkehrsverbund Rhein-Ruhr (VRR) | vrr-trias | TRIAS 1.2 | |
| Verkehrsverbund Rhein-Ruhr (VRR) | vrr-ojp | OJP 1.0 | |
| Österreichische Bundesbahnen (ÖBB) | oebb-hafas | HAFAS mgate | |
| Oberösterreichischer Verkehrsverbund (OÖVV) | ooevv-hafas | HAFAS mgate | |
| Routenauskunft Land Saltzburg | salzburg-hafas | HAFAS mgate | |
| Steirischer Verkehrsverbund (Verbundlinie) | stv-hafas | HAFAS mgate | |
| Salzburg Verkehr (SVV) | svv-hafas | HAFAS mgate | |
| Kärntner Linien/Verkehrsverbund Kärnten (VKG/VVK) | vkg-hafas | HAFAS mgate | |
| Verkehrsverbund Ostregion (VOR) | vor-hafas | HAFAS mgate | |
| Verkehrsverbund Tirol (VVT) | vvt-hafas | HAFAS mgate | |
| Verkehrsverbund Vorarlberg (VVV) | vvv-hafas | HAFAS mgate | |
| Transports publics genevois (TPG) | tpg-hafas | HAFAS mgate | |
| Aachener Verkehrsverbund (AVV) | avv-hafas | HAFAS mgate | |
| Berliner Verkehrsbetriebe (BVG) | bvg-hafas | HAFAS mgate | |
| Dallas Area Rapid Transit (DART) | dart-hafas | HAFAS mgate | |
| DB Busradar NRW | db-busradar-nrw-hafas | HAFAS mgate | |
| S-Bahn München | db-sbahn-muenchen-hafas | HAFAS mgate | |
| Deutsche Bahn (DB) | db-smartrbl-hafas | HAFAS mgate | |
| ÜSTRA Hannover (GVH) | gvh-hafas | HAFAS mgate | |
| Ingolstädter Verkehrsgesellschaft (INVG) | invg-hafas | HAFAS mgate | |
| Kölner Verkehrs-Betriebe (KVB) | kvb-hafas | HAFAS mgate | |
| Nahverkehrsverbund Schleswig-Holstein (NAH.SH) | nahsh-hafas | HAFAS mgate | |
| Personennahverkehr in Sachsen-Anhalt (NASA/INSA) | nasa-hafas | HAFAS mgate | |
| Nordhessischer Verkehrsverbund (NVV) | nvv-hafas | HAFAS mgate | |
| Rhein-Main-Verkehrsverbund (RMV) | rmv-hafas | HAFAS mgate | |
| Rostocker Straßenbahn (RSAG) | rsag-hafas | HAFAS mgate | |
| Saarländischer Verkehrsverbund (SaarVV) | saarvv-hafas | HAFAS mgate | |
| Verkehrsverbund Berlin-Brandenburg (VBB) | vbb-hafas | HAFAS mgate | |
| Verkehrsverbund Bremen/Niedersachsen (VBN) | vbn-hafas | HAFAS mgate | |
| Verkehrsverbund Mittelthüringen (VMT) | vmt-hafas | HAFAS mgate | |
| Verkehrsgemeinschaft Osnabrück (VOS) | vos-hafas | HAFAS mgate | |
| Verkehrsverbund Süd-Niedersachsen (VSN) | vsn-hafas | HAFAS mgate | |
| Rejseplanen | rejseplanen-hafas | HAFAS mgate | |
| Iarnród Éireann (Irish Rail) | iarnrod-eireann-hafas | HAFAS mgate | |
| mobilitéits zentral (mobiliteit.lu) | mobiliteit-lu-hafas | HAFAS mgate | |
| Resrobot | resrobot-hafas | HAFAS mgate | |
| Bay Area Rapid Transit (BART) | bart-hafas | HAFAS mgate | |
| Entur | entur | OpenTripPlanner | |
| Transitous open public transport routing | transitous | MOTIS |