Skip to content

transitmatters

Python client for the TransitMatters Data Dashboard API.

TransitMatters

TransitMatters(
    base_url: str = DEFAULT_BASE_URL,
    *,
    timeout: float | Timeout | None = DEFAULT_TIMEOUT,
    max_retries: int = DEFAULT_MAX_RETRIES,
    max_concurrency: int = DEFAULT_MAX_CONCURRENCY,
    headers: Mapping[str, str] | None = None,
    httpx_args: Mapping[str, Any] | None = None,
)

Bases: _BaseClient

Client for the TransitMatters Data Dashboard API.

Use it as a context manager, or call close when finished, to release the connection pool. Methods raise transitmatters.APIError when the API returns an error, and transitmatters.NetworkError when no response arrives.

Methods that take a route or line accept a transitmatters.Line, and send the ID each endpoint expects for it. For other routes, pass the ID string shown in each method's docstring; routes and stops list them.

Dates are service dates: service after midnight, until about 3:30 AM, belongs to the day before. Date ranges include both ends.

Source code in src/transitmatters/client.py
def __init__(
    self,
    base_url: str = DEFAULT_BASE_URL,
    *,
    timeout: float | httpx.Timeout | None = DEFAULT_TIMEOUT,
    max_retries: int = DEFAULT_MAX_RETRIES,
    max_concurrency: int = DEFAULT_MAX_CONCURRENCY,
    headers: Mapping[str, str] | None = None,
    httpx_args: Mapping[str, Any] | None = None,
) -> None:
    """
    Args:
        base_url: API root. Defaults to the production API.
        timeout: Seconds to wait for each request, an `httpx.Timeout`,
            or `None` to wait indefinitely.
        max_retries: How many times to retry a request that timed out,
            couldn't connect, or got a 429, 502, 503, or 504, with
            exponential backoff. `0` disables retries.
        max_concurrency: How many requests to have in flight at once
            when a method makes several, such as `headways` over a date
            range.
        headers: Extra headers to send with every request.
        httpx_args: Extra keyword arguments for the underlying `httpx`
            client, such as `transport` or `proxy`.
    """
    if isinstance(timeout, int | float):
        timeout = httpx.Timeout(timeout)
    if max_concurrency < 1:
        raise ValueError("max_concurrency must be at least 1")
    self._max_retries = max_retries
    self._max_concurrency = max_concurrency
    self._client = Client(
        base_url=base_url,
        timeout=timeout,
        headers=dict(headers or {}),
        httpx_args=dict(httpx_args or {}),
    )

close

close() -> None

Close the underlying connection pool.

Source code in src/transitmatters/client.py
def close(self) -> None:
    """Close the underlying connection pool."""
    self._client.get_httpx_client().close()

healthcheck

healthcheck() -> Healthcheck

Run the API's health checks.

Failing checks come back with ok false rather than raising.

Source code in src/transitmatters/client.py
def healthcheck(self) -> Healthcheck:
    """Run the API's health checks.

    Failing checks come back with `ok` false rather than raising.
    """
    return self._run(ep.healthcheck(self._client))

headways

headways(
    date: DateLike,
    end_date: DateLike | None = None,
    *,
    stop: OneOrMany | None = None,
) -> list[Headway]

Time between consecutive departures from stop on date, or on each day from date through end_date.

Returns one event per departure. stop is one or more MBTA stop IDs, e.g. "70061". Over a range, days are fetched concurrently.

Source code in src/transitmatters/client.py
def headways(
    self,
    date: DateLike,
    end_date: DateLike | None = None,
    *,
    stop: OneOrMany | None = None,
) -> list[Headway]:
    """Time between consecutive departures from `stop` on `date`, or on
    each day from `date` through `end_date`.

    Returns one event per departure. `stop` is one or more MBTA stop IDs,
    e.g. `"70061"`. Over a range, days are fetched concurrently.
    """
    return self._run_all(ep.headways(self._client, date, end_date, stop=stop))

dwells

dwells(
    date: DateLike,
    end_date: DateLike | None = None,
    *,
    stop: OneOrMany | None = None,
) -> list[Dwell]

Time vehicles spent stopped at stop on date, or on each day from date through end_date.

Returns one event per stop a vehicle made. stop is one or more MBTA stop IDs, e.g. "70061".

Source code in src/transitmatters/client.py
def dwells(
    self,
    date: DateLike,
    end_date: DateLike | None = None,
    *,
    stop: OneOrMany | None = None,
) -> list[Dwell]:
    """Time vehicles spent stopped at `stop` on `date`, or on each day
    from `date` through `end_date`.

    Returns one event per stop a vehicle made. `stop` is one or more MBTA
    stop IDs, e.g. `"70061"`.
    """
    return self._run_all(ep.dwells(self._client, date, end_date, stop=stop))

travel_times

travel_times(
    date: DateLike,
    end_date: DateLike | None = None,
    *,
    from_stop: OneOrMany | None = None,
    to_stop: OneOrMany | None = None,
) -> list[TravelTime]

Travel time of each trip from from_stop to to_stop on date, or on each day from date through end_date.

Returns one event per trip. Both are one or more MBTA stop IDs, e.g. "70061", and must be platforms for the same direction of travel; transitmatters.models.RouteStops.trip finds them.

Source code in src/transitmatters/client.py
def travel_times(
    self,
    date: DateLike,
    end_date: DateLike | None = None,
    *,
    from_stop: OneOrMany | None = None,
    to_stop: OneOrMany | None = None,
) -> list[TravelTime]:
    """Travel time of each trip from `from_stop` to `to_stop` on `date`,
    or on each day from `date` through `end_date`.

    Returns one event per trip. Both are one or more MBTA stop IDs, e.g.
    `"70061"`, and must be platforms for the same direction of travel;
    `transitmatters.models.RouteStops.trip` finds them.
    """
    return self._run_all(
        ep.travel_times(
            self._client, date, end_date, from_stop=from_stop, to_stop=to_stop
        )
    )

historical_alerts

historical_alerts(
    date: DateLike,
    end_date: DateLike | None = None,
    *,
    route: RouteLike | Sequence[RouteLike] | None = None,
) -> list[Alert]

Alerts that were active for route on date, or on any day from date through end_date.

route is one or more Lines or MBTA route IDs, e.g. Line.RED or "66". An alert active on several days is returned once.

Source code in src/transitmatters/client.py
def historical_alerts(
    self,
    date: DateLike,
    end_date: DateLike | None = None,
    *,
    route: RouteLike | Sequence[RouteLike] | None = None,
) -> list[Alert]:
    """Alerts that were active for `route` on `date`, or on any day from
    `date` through `end_date`.

    `route` is one or more `Line`s or MBTA route IDs, e.g. `Line.RED` or
    `"66"`. An alert active on several days is returned once.
    """
    return ep.unique_alerts(
        self._run_all(
            ep.historical_alerts(self._client, date, end_date, route=route)
        )
    )

aggregate_travel_times

aggregate_travel_times(
    start_date: DateLike,
    end_date: DateLike,
    *,
    from_stop: OneOrMany | None = None,
    to_stop: OneOrMany | None = None,
) -> list[DailyStats]

Daily travel-time statistics between stops over an inclusive date range.

Returns one entry per service date and peak period. Stop IDs work as in travel_times.

Source code in src/transitmatters/client.py
def aggregate_travel_times(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    from_stop: OneOrMany | None = None,
    to_stop: OneOrMany | None = None,
) -> list[DailyStats]:
    """Daily travel-time statistics between stops over an inclusive date range.

    Returns one entry per service date and peak period. Stop IDs work as
    in `travel_times`.
    """
    return self._run(
        ep.aggregate_travel_times(
            self._client, start_date, end_date, from_stop=from_stop, to_stop=to_stop
        )
    )

aggregate_travel_times_v2

aggregate_travel_times_v2(
    start_date: DateLike,
    end_date: DateLike,
    *,
    from_stop: OneOrMany | None = None,
    to_stop: OneOrMany | None = None,
) -> TravelTimeStats

Travel-time statistics between stops, by date and by time of day.

by_date matches aggregate_travel_times; by_time groups trips into 30-minute departure-time buckets across the whole range.

Source code in src/transitmatters/client.py
def aggregate_travel_times_v2(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    from_stop: OneOrMany | None = None,
    to_stop: OneOrMany | None = None,
) -> TravelTimeStats:
    """Travel-time statistics between stops, by date and by time of day.

    `by_date` matches `aggregate_travel_times`; `by_time` groups trips into
    30-minute departure-time buckets across the whole range.
    """
    return self._run(
        ep.aggregate_travel_times_v2(
            self._client, start_date, end_date, from_stop=from_stop, to_stop=to_stop
        )
    )

aggregate_headways

aggregate_headways(
    start_date: DateLike,
    end_date: DateLike,
    *,
    stop: OneOrMany | None = None,
) -> list[DailyHeadwayStats]

Daily headway statistics for stop over an inclusive date range.

Returns one entry per service date, with bunching and on-time counts.

Source code in src/transitmatters/client.py
def aggregate_headways(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    stop: OneOrMany | None = None,
) -> list[DailyHeadwayStats]:
    """Daily headway statistics for `stop` over an inclusive date range.

    Returns one entry per service date, with bunching and on-time counts.
    """
    return self._run(
        ep.aggregate_headways(self._client, start_date, end_date, stop=stop)
    )

aggregate_dwells

aggregate_dwells(
    start_date: DateLike,
    end_date: DateLike,
    *,
    stop: OneOrMany | None = None,
) -> list[DailyStats]

Daily dwell-time statistics for stop over an inclusive date range.

Returns one entry per service date and peak period.

Source code in src/transitmatters/client.py
def aggregate_dwells(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    stop: OneOrMany | None = None,
) -> list[DailyStats]:
    """Daily dwell-time statistics for `stop` over an inclusive date range.

    Returns one entry per service date and peak period.
    """
    return self._run(
        ep.aggregate_dwells(self._client, start_date, end_date, stop=stop)
    )

current_alerts

current_alerts() -> list[LiveAlert]

Alerts in effect right now, live from the MBTA.

Source code in src/transitmatters/client.py
def current_alerts(self) -> list[LiveAlert]:
    """Alerts in effect right now, live from the MBTA."""
    return self._run(ep.current_alerts(self._client))

line_delays

line_delays(
    start_date: DateLike,
    end_date: DateLike,
    *,
    line: RouteLike,
    agg: Literal["daily", "weekly"] = "weekly",
) -> list[LineDelays]

Alert-attributed delays on line over an inclusive date range.

Returns one entry per day or week, with minutes of delay by cause. line is a Line or a commuter rail route ID, e.g. "CR-Fairmount". The Green Line is reported by branch, so pass e.g. "Green-B" rather than Line.GREEN.

Source code in src/transitmatters/client.py
def line_delays(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    line: RouteLike,
    agg: Literal["daily", "weekly"] = "weekly",
) -> list[LineDelays]:
    """Alert-attributed delays on `line` over an inclusive date range.

    Returns one entry per day or week, with minutes of delay by cause.
    `line` is a `Line` or a commuter rail route ID, e.g. `"CR-Fairmount"`.
    The Green Line is reported by branch, so pass e.g. `"Green-B"`
    rather than `Line.GREEN`.
    """
    return self._run(
        ep.line_delays(self._client, start_date, end_date, line=line, agg=agg)
    )

trip_metrics

trip_metrics(
    start_date: DateLike,
    end_date: DateLike,
    *,
    line: RouteLike,
    agg: Agg,
) -> list[TripMetrics]

Speed and travel-time metrics for line over an inclusive date range.

Returns one entry per day, week, or month. line is a rapid transit Line, or its key, e.g. "line-red". The API returns at most 150 entries per request, so longer ranges are fetched in pieces.

Source code in src/transitmatters/client.py
def trip_metrics(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    line: RouteLike,
    agg: Agg,
) -> list[TripMetrics]:
    """Speed and travel-time metrics for `line` over an inclusive date range.

    Returns one entry per day, week, or month. `line` is a rapid transit
    `Line`, or its key, e.g. `"line-red"`. The API returns at most 150
    entries per request, so longer ranges are fetched in pieces.
    """
    return ep.unique_by_date(
        self._run_all(
            ep.trip_metrics(self._client, start_date, end_date, line=line, agg=agg)
        )
    )

bus_trip_metrics

bus_trip_metrics(
    start_date: DateLike,
    end_date: DateLike,
    *,
    route: OneOrMany,
    agg: Agg,
    time_band: TimeBand | None = None,
    day_type: DayType | None = None,
) -> list[BusTripMetrics]

Speed and trip metrics for a bus route over an inclusive date range.

Returns one entry per day, week, or month. route is a bus route ID, e.g. "1", or several, whose trips are added together. Trip counts and speeds start in December 2025.

time_band limits the figures to one time of day: "early_am", "am_peak", "midday", "pm_peak", "evening", or "late_night". day_type keeps only "business_day"s or only "weekend_or_holiday"s. The API returns at most 150 entries per request, so longer ranges are fetched in pieces.

Source code in src/transitmatters/client.py
def bus_trip_metrics(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    route: OneOrMany,
    agg: Agg,
    time_band: TimeBand | None = None,
    day_type: DayType | None = None,
) -> list[BusTripMetrics]:
    """Speed and trip metrics for a bus route over an inclusive date range.

    Returns one entry per day, week, or month. `route` is a bus route
    ID, e.g. `"1"`, or several, whose trips are added together. Trip
    counts and speeds start in December 2025.

    `time_band` limits the figures to one time of day: `"early_am"`,
    `"am_peak"`, `"midday"`, `"pm_peak"`, `"evening"`, or
    `"late_night"`. `day_type` keeps only `"business_day"`s or only
    `"weekend_or_holiday"`s. The API returns at most 150 entries per
    request, so longer ranges are fetched in pieces.
    """
    return self._run_all(
        ep.bus_trip_metrics(
            self._client,
            start_date,
            end_date,
            route=route,
            agg=agg,
            time_band=time_band,
            day_type=day_type,
        )
    )

commuter_rail_trip_metrics

commuter_rail_trip_metrics(
    start_date: DateLike,
    end_date: DateLike,
    *,
    route: str,
    agg: Agg,
) -> list[CommuterRailTripMetrics]

The fleet that ran a commuter rail route over an inclusive date range.

Returns one entry per day, week, or month. route is a commuter rail route ID, e.g. "CR-Fairmount", or "all" for the whole system. Longer ranges are fetched in pieces, as in bus_trip_metrics.

Source code in src/transitmatters/client.py
def commuter_rail_trip_metrics(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    route: str,
    agg: Agg,
) -> list[CommuterRailTripMetrics]:
    """The fleet that ran a commuter rail route over an inclusive date range.

    Returns one entry per day, week, or month. `route` is a commuter rail
    route ID, e.g. `"CR-Fairmount"`, or `"all"` for the whole system.
    Longer ranges are fetched in pieces, as in `bus_trip_metrics`.
    """
    return self._run_all(
        ep.commuter_rail_trip_metrics(
            self._client, start_date, end_date, route=route, agg=agg
        )
    )

bus_speed_leaderboard

bus_speed_leaderboard(
    start_date: DateLike,
    end_date: DateLike,
    *,
    limit: int = 10,
) -> list[BusRouteSpeed]

The slowest bus routes over an inclusive date range, slowest first.

Returns up to limit routes, at most 200, with their totals over the range. Ranges over 150 days raise transitmatters.RangeTooLongError.

Source code in src/transitmatters/client.py
def bus_speed_leaderboard(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    limit: int = 10,
) -> list[BusRouteSpeed]:
    """The slowest bus routes over an inclusive date range, slowest first.

    Returns up to `limit` routes, at most 200, with their totals over the
    range. Ranges over 150 days raise `transitmatters.RangeTooLongError`.
    """
    return self._run(
        ep.bus_speed_leaderboard(self._client, start_date, end_date, limit=limit)
    )

scheduled_service

scheduled_service(
    start_date: DateLike,
    end_date: DateLike,
    *,
    route: RouteLike,
    agg: Agg,
) -> ScheduledService

Scheduled trip counts for route over an inclusive date range.

counts has one entry per day, week, or month. route is a Line or an MBTA route ID, e.g. "66".

Source code in src/transitmatters/client.py
def scheduled_service(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    route: RouteLike,
    agg: Agg,
) -> ScheduledService:
    """Scheduled trip counts for `route` over an inclusive date range.

    `counts` has one entry per day, week, or month. `route` is a `Line` or
    an MBTA route ID, e.g. `"66"`.
    """
    return self._run(
        ep.scheduled_service(
            self._client, start_date, end_date, route=route, agg=agg
        )
    )

ridership

ridership(
    start_date: DateLike,
    end_date: DateLike,
    *,
    line: RouteLike,
) -> list[Ridership]

Ridership on line over an inclusive date range.

Returns one entry per week. line is a Line or a GTFS line ID, e.g. "line-66" or "line-Fairmount".

Source code in src/transitmatters/client.py
def ridership(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    line: RouteLike,
) -> list[Ridership]:
    """Ridership on `line` over an inclusive date range.

    Returns one entry per week. `line` is a `Line` or a GTFS line ID, e.g.
    `"line-66"` or `"line-Fairmount"`.
    """
    return self._run(ep.ridership(self._client, start_date, end_date, line=line))

facilities

facilities() -> list[Facility]

Elevators and escalators, live from the MBTA.

Source code in src/transitmatters/client.py
def facilities(self) -> list[Facility]:
    """Elevators and escalators, live from the MBTA."""
    return self._run(ep.facilities(self._client))

speed_restrictions

speed_restrictions(
    date: DateLike, *, line: RouteLike
) -> SpeedRestrictions

Speed restrictions in effect on a rapid transit line on date.

line is a Line, or its case-sensitive GTFS ID, e.g. "line-Red".

Source code in src/transitmatters/client.py
def speed_restrictions(
    self, date: DateLike, *, line: RouteLike
) -> SpeedRestrictions:
    """Speed restrictions in effect on a rapid transit line on `date`.

    `line` is a `Line`, or its case-sensitive GTFS ID, e.g. `"line-Red"`.
    """
    return self._run(ep.speed_restrictions(self._client, date, line=line))

service_hours

service_hours(
    start_date: DateLike,
    end_date: DateLike,
    *,
    line: RouteLike,
    agg: Agg,
) -> list[ServiceHours]

Scheduled and delivered service hours on line over a date range.

Returns one entry per day, week, or month. line is a rapid transit Line, or its key, e.g. "line-red".

Source code in src/transitmatters/client.py
def service_hours(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    line: RouteLike,
    agg: Agg,
) -> list[ServiceHours]:
    """Scheduled and delivered service hours on `line` over a date range.

    Returns one entry per day, week, or month. `line` is a rapid transit
    `Line`, or its key, e.g. `"line-red"`.
    """
    return self._run(
        ep.service_hours(self._client, start_date, end_date, line=line, agg=agg)
    )

time_predictions

time_predictions(
    route: RouteLike,
    *,
    start_date: DateLike | None = None,
    end_date: DateLike | None = None,
) -> list[TimePredictionWeek]

Weekly arrival-prediction accuracy for route.

route is a Line or a route ID. The Green Line is reported by branch, so pass e.g. "Green-B" rather than Line.GREEN. Returns the whole history, or only weeks starting from start_date through end_date when given.

Source code in src/transitmatters/client.py
def time_predictions(
    self,
    route: RouteLike,
    *,
    start_date: DateLike | None = None,
    end_date: DateLike | None = None,
) -> list[TimePredictionWeek]:
    """Weekly arrival-prediction accuracy for `route`.

    `route` is a `Line` or a route ID. The Green Line is reported by
    branch, so pass e.g. `"Green-B"` rather than `Line.GREEN`. Returns
    the whole history, or only weeks starting from `start_date` through
    `end_date` when given.
    """
    return self._run(
        ep.time_predictions(
            self._client, route, start_date=start_date, end_date=end_date
        )
    )

reliability

reliability(
    start_date: DateLike,
    end_date: DateLike,
    *,
    route: str,
    agg: Agg,
) -> list[Reliability]

On-time performance of The RIDE or commuter rail over a date range.

Returns one entry per day, week, or month. route is "RIDE", a commuter rail route ID, e.g. "CR-Worcester", or "commuter-rail" for every commuter rail route combined.

Source code in src/transitmatters/client.py
def reliability(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    route: str,
    agg: Agg,
) -> list[Reliability]:
    """On-time performance of The RIDE or commuter rail over a date range.

    Returns one entry per day, week, or month. `route` is `"RIDE"`, a
    commuter rail route ID, e.g. `"CR-Worcester"`, or `"commuter-rail"`
    for every commuter rail route combined.
    """
    return self._run(
        ep.reliability(self._client, start_date, end_date, route=route, agg=agg)
    )

commuter_rail_scorecard

commuter_rail_scorecard(
    start_date: DateLike,
    end_date: DateLike,
    *,
    route: str,
    agg: Agg,
    day_kind: DayKind,
) -> list[CommuterRailScorecard]

A commuter rail schedule measured against Regional Rail standards.

route is a commuter rail route ID, e.g. "CR-Worcester", for one entry per day, week, or month. Or it's "commuter-rail", for one entry per route over the whole range, ignoring agg. day_kind is the schedule to measure: "weekday", "saturday", "sunday", or "all" for every day.

Source code in src/transitmatters/client.py
def commuter_rail_scorecard(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    route: str,
    agg: Agg,
    day_kind: DayKind,
) -> list[CommuterRailScorecard]:
    """A commuter rail schedule measured against Regional Rail standards.

    `route` is a commuter rail route ID, e.g. `"CR-Worcester"`, for one
    entry per day, week, or month. Or it's `"commuter-rail"`, for one
    entry per route over the whole range, ignoring `agg`. `day_kind` is
    the schedule to measure: `"weekday"`, `"saturday"`, `"sunday"`, or
    `"all"` for every day.
    """
    return self._run(
        ep.commuter_rail_scorecard(
            self._client,
            start_date,
            end_date,
            route=route,
            agg=agg,
            day_kind=day_kind,
        )
    )

weather

weather(
    start_date: DateLike, end_date: DateLike
) -> list[Weather]

Hourly weather in downtown Boston over an inclusive date range.

Data starts in April 2026. Days without data are left out.

Source code in src/transitmatters/client.py
def weather(self, start_date: DateLike, end_date: DateLike) -> list[Weather]:
    """Hourly weather in downtown Boston over an inclusive date range.

    Data starts in April 2026. Days without data are left out.
    """
    return self._run(ep.weather(self._client, start_date, end_date))

service_ridership_dashboard

service_ridership_dashboard() -> ServiceRidershipDashboard

Combined service and ridership data behind the overview dashboard.

Source code in src/transitmatters/client.py
def service_ridership_dashboard(self) -> ServiceRidershipDashboard:
    """Combined service and ridership data behind the overview dashboard."""
    return self._run(ep.service_ridership_dashboard(self._client))

routes

routes() -> Routes

All route IDs the dashboard supports, grouped by mode.

Source code in src/transitmatters/client.py
def routes(self) -> Routes:
    """All route IDs the dashboard supports, grouped by mode."""
    return self._run(ep.routes(self._client))

stops

stops(route: RouteLike) -> RouteStops

Stations along route, with the stop ID of each platform.

route is a Line or an MBTA route ID, e.g. "66". Use transitmatters.models.RouteStops.trip to find the stop IDs between two stations.

Source code in src/transitmatters/client.py
def stops(self, route: RouteLike) -> RouteStops:
    """Stations along `route`, with the stop ID of each platform.

    `route` is a `Line` or an MBTA route ID, e.g. `"66"`. Use
    `transitmatters.models.RouteStops.trip` to find the stop IDs between
    two stations.
    """
    return self._run(ep.stops(self._client, route))

AsyncTransitMatters

AsyncTransitMatters(
    base_url: str = DEFAULT_BASE_URL,
    *,
    timeout: float | Timeout | None = DEFAULT_TIMEOUT,
    max_retries: int = DEFAULT_MAX_RETRIES,
    max_concurrency: int = DEFAULT_MAX_CONCURRENCY,
    headers: Mapping[str, str] | None = None,
    httpx_args: Mapping[str, Any] | None = None,
)

Bases: _BaseClient

Async client for the TransitMatters Data Dashboard API.

Mirrors TransitMatters; see it for details on each method. Use it as an async context manager, or await aclose when finished.

Source code in src/transitmatters/client.py
def __init__(
    self,
    base_url: str = DEFAULT_BASE_URL,
    *,
    timeout: float | httpx.Timeout | None = DEFAULT_TIMEOUT,
    max_retries: int = DEFAULT_MAX_RETRIES,
    max_concurrency: int = DEFAULT_MAX_CONCURRENCY,
    headers: Mapping[str, str] | None = None,
    httpx_args: Mapping[str, Any] | None = None,
) -> None:
    """
    Args:
        base_url: API root. Defaults to the production API.
        timeout: Seconds to wait for each request, an `httpx.Timeout`,
            or `None` to wait indefinitely.
        max_retries: How many times to retry a request that timed out,
            couldn't connect, or got a 429, 502, 503, or 504, with
            exponential backoff. `0` disables retries.
        max_concurrency: How many requests to have in flight at once
            when a method makes several, such as `headways` over a date
            range.
        headers: Extra headers to send with every request.
        httpx_args: Extra keyword arguments for the underlying `httpx`
            client, such as `transport` or `proxy`.
    """
    if isinstance(timeout, int | float):
        timeout = httpx.Timeout(timeout)
    if max_concurrency < 1:
        raise ValueError("max_concurrency must be at least 1")
    self._max_retries = max_retries
    self._max_concurrency = max_concurrency
    self._client = Client(
        base_url=base_url,
        timeout=timeout,
        headers=dict(headers or {}),
        httpx_args=dict(httpx_args or {}),
    )

aclose async

aclose() -> None

Close the underlying connection pool.

Source code in src/transitmatters/client.py
async def aclose(self) -> None:
    """Close the underlying connection pool."""
    await self._client.get_async_httpx_client().aclose()

healthcheck async

healthcheck() -> Healthcheck

Run the API's health checks.

Failing checks come back with ok false rather than raising.

Source code in src/transitmatters/client.py
async def healthcheck(self) -> Healthcheck:
    """Run the API's health checks.

    Failing checks come back with `ok` false rather than raising.
    """
    return await self._run(ep.healthcheck(self._client))

headways async

headways(
    date: DateLike,
    end_date: DateLike | None = None,
    *,
    stop: OneOrMany | None = None,
) -> list[Headway]

Time between consecutive departures from stop on each day.

Source code in src/transitmatters/client.py
async def headways(
    self,
    date: DateLike,
    end_date: DateLike | None = None,
    *,
    stop: OneOrMany | None = None,
) -> list[Headway]:
    """Time between consecutive departures from `stop` on each day."""
    return await self._run_all(ep.headways(self._client, date, end_date, stop=stop))

dwells async

dwells(
    date: DateLike,
    end_date: DateLike | None = None,
    *,
    stop: OneOrMany | None = None,
) -> list[Dwell]

Time vehicles spent stopped at stop on each day.

Source code in src/transitmatters/client.py
async def dwells(
    self,
    date: DateLike,
    end_date: DateLike | None = None,
    *,
    stop: OneOrMany | None = None,
) -> list[Dwell]:
    """Time vehicles spent stopped at `stop` on each day."""
    return await self._run_all(ep.dwells(self._client, date, end_date, stop=stop))

travel_times async

travel_times(
    date: DateLike,
    end_date: DateLike | None = None,
    *,
    from_stop: OneOrMany | None = None,
    to_stop: OneOrMany | None = None,
) -> list[TravelTime]

Travel time of each trip from from_stop to to_stop on each day.

Source code in src/transitmatters/client.py
async def travel_times(
    self,
    date: DateLike,
    end_date: DateLike | None = None,
    *,
    from_stop: OneOrMany | None = None,
    to_stop: OneOrMany | None = None,
) -> list[TravelTime]:
    """Travel time of each trip from `from_stop` to `to_stop` on each day."""
    return await self._run_all(
        ep.travel_times(
            self._client, date, end_date, from_stop=from_stop, to_stop=to_stop
        )
    )

historical_alerts async

historical_alerts(
    date: DateLike,
    end_date: DateLike | None = None,
    *,
    route: RouteLike | Sequence[RouteLike] | None = None,
) -> list[Alert]

Alerts that were active for route on any of the days.

Source code in src/transitmatters/client.py
async def historical_alerts(
    self,
    date: DateLike,
    end_date: DateLike | None = None,
    *,
    route: RouteLike | Sequence[RouteLike] | None = None,
) -> list[Alert]:
    """Alerts that were active for `route` on any of the days."""
    return ep.unique_alerts(
        await self._run_all(
            ep.historical_alerts(self._client, date, end_date, route=route)
        )
    )

aggregate_travel_times async

aggregate_travel_times(
    start_date: DateLike,
    end_date: DateLike,
    *,
    from_stop: OneOrMany | None = None,
    to_stop: OneOrMany | None = None,
) -> list[DailyStats]

Daily travel-time statistics between stops over an inclusive date range.

Source code in src/transitmatters/client.py
async def aggregate_travel_times(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    from_stop: OneOrMany | None = None,
    to_stop: OneOrMany | None = None,
) -> list[DailyStats]:
    """Daily travel-time statistics between stops over an inclusive date range."""
    return await self._run(
        ep.aggregate_travel_times(
            self._client, start_date, end_date, from_stop=from_stop, to_stop=to_stop
        )
    )

aggregate_travel_times_v2 async

aggregate_travel_times_v2(
    start_date: DateLike,
    end_date: DateLike,
    *,
    from_stop: OneOrMany | None = None,
    to_stop: OneOrMany | None = None,
) -> TravelTimeStats

Travel-time statistics between stops, by date and by time of day.

Source code in src/transitmatters/client.py
async def aggregate_travel_times_v2(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    from_stop: OneOrMany | None = None,
    to_stop: OneOrMany | None = None,
) -> TravelTimeStats:
    """Travel-time statistics between stops, by date and by time of day."""
    return await self._run(
        ep.aggregate_travel_times_v2(
            self._client, start_date, end_date, from_stop=from_stop, to_stop=to_stop
        )
    )

aggregate_headways async

aggregate_headways(
    start_date: DateLike,
    end_date: DateLike,
    *,
    stop: OneOrMany | None = None,
) -> list[DailyHeadwayStats]

Daily headway statistics for stop over an inclusive date range.

Source code in src/transitmatters/client.py
async def aggregate_headways(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    stop: OneOrMany | None = None,
) -> list[DailyHeadwayStats]:
    """Daily headway statistics for `stop` over an inclusive date range."""
    return await self._run(
        ep.aggregate_headways(self._client, start_date, end_date, stop=stop)
    )

aggregate_dwells async

aggregate_dwells(
    start_date: DateLike,
    end_date: DateLike,
    *,
    stop: OneOrMany | None = None,
) -> list[DailyStats]

Daily dwell-time statistics for stop over an inclusive date range.

Source code in src/transitmatters/client.py
async def aggregate_dwells(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    stop: OneOrMany | None = None,
) -> list[DailyStats]:
    """Daily dwell-time statistics for `stop` over an inclusive date range."""
    return await self._run(
        ep.aggregate_dwells(self._client, start_date, end_date, stop=stop)
    )

current_alerts async

current_alerts() -> list[LiveAlert]

Alerts in effect right now, live from the MBTA.

Source code in src/transitmatters/client.py
async def current_alerts(self) -> list[LiveAlert]:
    """Alerts in effect right now, live from the MBTA."""
    return await self._run(ep.current_alerts(self._client))

line_delays async

line_delays(
    start_date: DateLike,
    end_date: DateLike,
    *,
    line: RouteLike,
    agg: Literal["daily", "weekly"] = "weekly",
) -> list[LineDelays]

Alert-attributed delays on line over an inclusive date range.

Source code in src/transitmatters/client.py
async def line_delays(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    line: RouteLike,
    agg: Literal["daily", "weekly"] = "weekly",
) -> list[LineDelays]:
    """Alert-attributed delays on `line` over an inclusive date range."""
    return await self._run(
        ep.line_delays(self._client, start_date, end_date, line=line, agg=agg)
    )

trip_metrics async

trip_metrics(
    start_date: DateLike,
    end_date: DateLike,
    *,
    line: RouteLike,
    agg: Agg,
) -> list[TripMetrics]

Speed and travel-time metrics for line over an inclusive date range.

Source code in src/transitmatters/client.py
async def trip_metrics(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    line: RouteLike,
    agg: Agg,
) -> list[TripMetrics]:
    """Speed and travel-time metrics for `line` over an inclusive date range."""
    return ep.unique_by_date(
        await self._run_all(
            ep.trip_metrics(self._client, start_date, end_date, line=line, agg=agg)
        )
    )

bus_trip_metrics async

bus_trip_metrics(
    start_date: DateLike,
    end_date: DateLike,
    *,
    route: OneOrMany,
    agg: Agg,
    time_band: TimeBand | None = None,
    day_type: DayType | None = None,
) -> list[BusTripMetrics]

Speed and trip metrics for a bus route over an inclusive date range.

Source code in src/transitmatters/client.py
async def bus_trip_metrics(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    route: OneOrMany,
    agg: Agg,
    time_band: TimeBand | None = None,
    day_type: DayType | None = None,
) -> list[BusTripMetrics]:
    """Speed and trip metrics for a bus route over an inclusive date range."""
    return await self._run_all(
        ep.bus_trip_metrics(
            self._client,
            start_date,
            end_date,
            route=route,
            agg=agg,
            time_band=time_band,
            day_type=day_type,
        )
    )

commuter_rail_trip_metrics async

commuter_rail_trip_metrics(
    start_date: DateLike,
    end_date: DateLike,
    *,
    route: str,
    agg: Agg,
) -> list[CommuterRailTripMetrics]

The fleet that ran a commuter rail route over an inclusive date range.

Source code in src/transitmatters/client.py
async def commuter_rail_trip_metrics(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    route: str,
    agg: Agg,
) -> list[CommuterRailTripMetrics]:
    """The fleet that ran a commuter rail route over an inclusive date range."""
    return await self._run_all(
        ep.commuter_rail_trip_metrics(
            self._client, start_date, end_date, route=route, agg=agg
        )
    )

bus_speed_leaderboard async

bus_speed_leaderboard(
    start_date: DateLike,
    end_date: DateLike,
    *,
    limit: int = 10,
) -> list[BusRouteSpeed]

The slowest bus routes over an inclusive date range, slowest first.

Source code in src/transitmatters/client.py
async def bus_speed_leaderboard(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    limit: int = 10,
) -> list[BusRouteSpeed]:
    """The slowest bus routes over an inclusive date range, slowest first."""
    return await self._run(
        ep.bus_speed_leaderboard(self._client, start_date, end_date, limit=limit)
    )

scheduled_service async

scheduled_service(
    start_date: DateLike,
    end_date: DateLike,
    *,
    route: RouteLike,
    agg: Agg,
) -> ScheduledService

Scheduled trip counts for route over an inclusive date range.

Source code in src/transitmatters/client.py
async def scheduled_service(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    route: RouteLike,
    agg: Agg,
) -> ScheduledService:
    """Scheduled trip counts for `route` over an inclusive date range."""
    return await self._run(
        ep.scheduled_service(
            self._client, start_date, end_date, route=route, agg=agg
        )
    )

ridership async

ridership(
    start_date: DateLike,
    end_date: DateLike,
    *,
    line: RouteLike,
) -> list[Ridership]

Ridership on line over an inclusive date range.

Source code in src/transitmatters/client.py
async def ridership(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    line: RouteLike,
) -> list[Ridership]:
    """Ridership on `line` over an inclusive date range."""
    return await self._run(
        ep.ridership(self._client, start_date, end_date, line=line)
    )

facilities async

facilities() -> list[Facility]

Elevators and escalators, live from the MBTA.

Source code in src/transitmatters/client.py
async def facilities(self) -> list[Facility]:
    """Elevators and escalators, live from the MBTA."""
    return await self._run(ep.facilities(self._client))

speed_restrictions async

speed_restrictions(
    date: DateLike, *, line: RouteLike
) -> SpeedRestrictions

Speed restrictions in effect on a rapid transit line on date.

Source code in src/transitmatters/client.py
async def speed_restrictions(
    self, date: DateLike, *, line: RouteLike
) -> SpeedRestrictions:
    """Speed restrictions in effect on a rapid transit line on `date`."""
    return await self._run(ep.speed_restrictions(self._client, date, line=line))

service_hours async

service_hours(
    start_date: DateLike,
    end_date: DateLike,
    *,
    line: RouteLike,
    agg: Agg,
) -> list[ServiceHours]

Scheduled and delivered service hours on line over a date range.

Source code in src/transitmatters/client.py
async def service_hours(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    line: RouteLike,
    agg: Agg,
) -> list[ServiceHours]:
    """Scheduled and delivered service hours on `line` over a date range."""
    return await self._run(
        ep.service_hours(self._client, start_date, end_date, line=line, agg=agg)
    )

time_predictions async

time_predictions(
    route: RouteLike,
    *,
    start_date: DateLike | None = None,
    end_date: DateLike | None = None,
) -> list[TimePredictionWeek]

Weekly arrival-prediction accuracy for route.

Source code in src/transitmatters/client.py
async def time_predictions(
    self,
    route: RouteLike,
    *,
    start_date: DateLike | None = None,
    end_date: DateLike | None = None,
) -> list[TimePredictionWeek]:
    """Weekly arrival-prediction accuracy for `route`."""
    return await self._run(
        ep.time_predictions(
            self._client, route, start_date=start_date, end_date=end_date
        )
    )

reliability async

reliability(
    start_date: DateLike,
    end_date: DateLike,
    *,
    route: str,
    agg: Agg,
) -> list[Reliability]

On-time performance of The RIDE or commuter rail over a date range.

Source code in src/transitmatters/client.py
async def reliability(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    route: str,
    agg: Agg,
) -> list[Reliability]:
    """On-time performance of The RIDE or commuter rail over a date range."""
    return await self._run(
        ep.reliability(self._client, start_date, end_date, route=route, agg=agg)
    )

commuter_rail_scorecard async

commuter_rail_scorecard(
    start_date: DateLike,
    end_date: DateLike,
    *,
    route: str,
    agg: Agg,
    day_kind: DayKind,
) -> list[CommuterRailScorecard]

A commuter rail schedule measured against Regional Rail standards.

Source code in src/transitmatters/client.py
async def commuter_rail_scorecard(
    self,
    start_date: DateLike,
    end_date: DateLike,
    *,
    route: str,
    agg: Agg,
    day_kind: DayKind,
) -> list[CommuterRailScorecard]:
    """A commuter rail schedule measured against Regional Rail standards."""
    return await self._run(
        ep.commuter_rail_scorecard(
            self._client,
            start_date,
            end_date,
            route=route,
            agg=agg,
            day_kind=day_kind,
        )
    )

weather async

weather(
    start_date: DateLike, end_date: DateLike
) -> list[Weather]

Hourly weather in downtown Boston over an inclusive date range.

Source code in src/transitmatters/client.py
async def weather(self, start_date: DateLike, end_date: DateLike) -> list[Weather]:
    """Hourly weather in downtown Boston over an inclusive date range."""
    return await self._run(ep.weather(self._client, start_date, end_date))

service_ridership_dashboard async

service_ridership_dashboard() -> ServiceRidershipDashboard

Combined service and ridership data behind the overview dashboard.

Source code in src/transitmatters/client.py
async def service_ridership_dashboard(self) -> ServiceRidershipDashboard:
    """Combined service and ridership data behind the overview dashboard."""
    return await self._run(ep.service_ridership_dashboard(self._client))

routes async

routes() -> Routes

All route IDs the dashboard supports, grouped by mode.

Source code in src/transitmatters/client.py
async def routes(self) -> Routes:
    """All route IDs the dashboard supports, grouped by mode."""
    return await self._run(ep.routes(self._client))

stops async

stops(route: RouteLike) -> RouteStops

Stations along route, with the stop ID of each platform.

Source code in src/transitmatters/client.py
async def stops(self, route: RouteLike) -> RouteStops:
    """Stations along `route`, with the stop ID of each platform."""
    return await self._run(ep.stops(self._client, route))

Line

Bases: Enum

A rapid transit line.

Methods that take a route or line ID also take a Line. Strings are passed through unchanged, so use them for buses ("66"), commuter rail ("CR-Fairmount"), ferries, and Green Line branches ("Green-B").

route_id property

route_id: str

Route ID, e.g. "Red", as stops and scheduled_service expect.

key property

key: str

Lowercase line key, e.g. "line-red", as trip_metrics and service_hours expect.

gtfs_line_id property

gtfs_line_id: str

GTFS line ID, e.g. "line-Red", as ridership and speed_restrictions expect.

branches property

branches: tuple[str, ...]

Route IDs of the line's branches: ("Green-B", ...) for the Green Line, empty for the others.

TransitMattersError

Bases: Exception

Base class for all errors raised by this library.

APIError

APIError(
    status_code: int,
    message: str,
    *,
    code: str | None = None,
    content: bytes = b"",
)

Bases: TransitMattersError

The API responded with an error status.

Attributes:

Name Type Description
status_code

HTTP status of the response.

message

Description of the problem, taken from the response body.

code

Error type reported by the API (e.g. BadRequestError), if any.

content

Raw response body.

Source code in src/transitmatters/errors.py
def __init__(
    self,
    status_code: int,
    message: str,
    *,
    code: str | None = None,
    content: bytes = b"",
) -> None:
    self.status_code = status_code
    self.message = message
    self.code = code
    self.content = content
    prefix = f"{status_code} {code}" if code else str(status_code)
    super().__init__(f"{prefix}: {message}")

BadRequestError

BadRequestError(
    status_code: int,
    message: str,
    *,
    code: str | None = None,
    content: bytes = b"",
)

Bases: APIError

The API rejected a parameter as missing or invalid (HTTP 400).

Source code in src/transitmatters/errors.py
def __init__(
    self,
    status_code: int,
    message: str,
    *,
    code: str | None = None,
    content: bytes = b"",
) -> None:
    self.status_code = status_code
    self.message = message
    self.code = code
    self.content = content
    prefix = f"{status_code} {code}" if code else str(status_code)
    super().__init__(f"{prefix}: {message}")

NotFoundError

NotFoundError(
    status_code: int,
    message: str,
    *,
    code: str | None = None,
    content: bytes = b"",
)

Bases: APIError

The requested route doesn't exist (HTTP 404).

Source code in src/transitmatters/errors.py
def __init__(
    self,
    status_code: int,
    message: str,
    *,
    code: str | None = None,
    content: bytes = b"",
) -> None:
    self.status_code = status_code
    self.message = message
    self.code = code
    self.content = content
    prefix = f"{status_code} {code}" if code else str(status_code)
    super().__init__(f"{prefix}: {message}")

RangeTooLongError

RangeTooLongError(
    status_code: int,
    message: str,
    *,
    code: str | None = None,
    content: bytes = b"",
)

Bases: APIError

The date range is too long for the endpoint (HTTP 403).

The trip metrics methods, such as TransitMatters.trip_metrics, split long ranges to avoid this. TransitMatters.bus_speed_leaderboard can't, so it raises this for ranges over 150 days.

Source code in src/transitmatters/errors.py
def __init__(
    self,
    status_code: int,
    message: str,
    *,
    code: str | None = None,
    content: bytes = b"",
) -> None:
    self.status_code = status_code
    self.message = message
    self.code = code
    self.content = content
    prefix = f"{status_code} {code}" if code else str(status_code)
    super().__init__(f"{prefix}: {message}")

ServerError

ServerError(
    status_code: int,
    message: str,
    *,
    code: str | None = None,
    content: bytes = b"",
)

Bases: APIError

The API failed to handle the request (HTTP 5xx).

Source code in src/transitmatters/errors.py
def __init__(
    self,
    status_code: int,
    message: str,
    *,
    code: str | None = None,
    content: bytes = b"",
) -> None:
    self.status_code = status_code
    self.message = message
    self.code = code
    self.content = content
    prefix = f"{status_code} {code}" if code else str(status_code)
    super().__init__(f"{prefix}: {message}")

NetworkError

Bases: TransitMattersError

The request failed before a response arrived, e.g. a timeout.

The underlying httpx exception is the __cause__.

to_dataframe

to_dataframe(items: Iterable[Model]) -> DataFrame

A DataFrame with one row per model and one column per field.

from transitmatters import to_dataframe

df = to_dataframe(tm.headways("2025-03-04", stop="70061"))
df.set_index("current_dep_dt")["headway_time_sec"].plot()

Times become timezone-aware datetime64 columns in Eastern time, and dates become datetime64 columns at midnight. Nested models, such as transitmatters.models.TimePredictionWeek.prediction, stay as objects; pass the nested list to to_dataframe instead. An empty list gives an empty DataFrame.

Needs pandas: pip install 'transitmatters[pandas]'.

Raises:

Type Description
TypeError

The items aren't all the same model.

Source code in src/transitmatters/_dataframe.py
def to_dataframe(items: Iterable[Model]) -> pandas.DataFrame:
    """A DataFrame with one row per model and one column per field.

    ```python
    from transitmatters import to_dataframe

    df = to_dataframe(tm.headways("2025-03-04", stop="70061"))
    df.set_index("current_dep_dt")["headway_time_sec"].plot()
    ```

    Times become timezone-aware `datetime64` columns in Eastern time, and
    dates become `datetime64` columns at midnight. Nested models, such as
    `transitmatters.models.TimePredictionWeek.prediction`, stay as objects;
    pass the nested list to `to_dataframe` instead. An empty list gives an
    empty DataFrame.

    Needs pandas: `pip install 'transitmatters[pandas]'`.

    Raises:
        TypeError: The items aren't all the same model.
    """
    try:
        import pandas
    except ImportError as e:
        raise ImportError(
            "to_dataframe needs pandas: pip install 'transitmatters[pandas]'"
        ) from e

    items = list(items)
    if not items:
        return pandas.DataFrame()
    model = type(items[0])
    if not all(type(item) is model for item in items):
        kinds = sorted({type(item).__name__ for item in items})
        raise TypeError(f"items must all be the same model, not {', '.join(kinds)}")

    columns = [field.name for field in dataclasses.fields(model)]
    df = pandas.DataFrame(
        [[getattr(item, column) for column in columns] for item in items],
        columns=columns,
    )
    for column in columns:
        values = df[column].dropna()
        # pandas infers datetime and timedelta columns, but leaves dates as objects.
        if len(values) and all(_is_date(value) for value in values):
            df[column] = pandas.to_datetime(df[column])
    return df