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);
}
}