Metadata-Version: 2.4
Name: septa-api
Version: 0.2.0
Summary: Python API client for SEPTA real-time data, alerts, and schedules
Author: zackwag
License: MIT
Project-URL: Homepage, https://github.com/zackwag/septa-api
Project-URL: Issues, https://github.com/zackwag/septa-api/issues
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: aiohttp>=3.9.0
Requires-Dist: gtfs-realtime-bindings>=3.0.0
Dynamic: license-file

# septa-api

Async Python client for [SEPTA](https://www.septa.org/) real-time data: service alerts, Regional Rail departure boards and trip planning, bus and trolley positions, and stop departures for every bus, trolley, and subway route. Built for a Home Assistant integration, usable anywhere.

No API key needed. Not affiliated with SEPTA.

## Installation

```bash
pip install septa-api
```

## Usage

```python
import asyncio

import aiohttp

from septa_api import SeptaClient, load_catalog


async def main():
    catalog = load_catalog()
    route = catalog.routes["B1"]
    northbound = next(d for d in route.directions if d.name == "Northbound")
    stop_id = northbound.stop_ids[0]

    async with aiohttp.ClientSession() as session:
        client = SeptaClient(session)

        alerts = await client.async_get_alerts()
        cancelled = {t for a in alerts if a.effect == "NO_SERVICE" for t in a.trip_ids}

        departures = await client.async_get_stop_departures(
            stop_id, route.id, results=3, cancelled_trip_ids=cancelled
        )
        for departure in departures:
            if departure.cancelled:
                label = "cancelled"
            else:
                label = "live" if departure.realtime else "scheduled"
            print(f"{catalog.stops[stop_id]}: {departure.expected:%H:%M} ({label})")

        for alert in alerts:
            if route.id in alert.route_ids:
                print(f"{alert.severity}: {alert.header}")


asyncio.run(main())
```

## Data sources

SEPTA's real-time data is spread over three systems, each with gaps. This library uses each one for what it does best.

| Data | Source | Notes |
| --- | --- | --- |
| Routes, directions, stops | Static GTFS, bundled | Refreshed daily by a workflow when SEPTA publishes a new release |
| Service alerts | GTFS-RT alert feeds | Every mode; uses the same route IDs as the catalog |
| Stop departures | JSON API timetable, plus live bus/trolley delay | Broad Street and Market-Frankford Lines are timetable only |
| Bus and trolley positions | JSON API (`TransitView`) | |
| Regional Rail departures and trips | JSON API (`Arrivals`, `NextToArrive`) | Live delays, tracks, and transfers |

SEPTA publishes no live predictions for the Broad Street Line or Market-Frankford Line. Their GTFS-RT trip updates are generated from the timetable, so this library doesn't pretend otherwise: their `StopDeparture.realtime` is always `False`.

## API

All times are timezone-aware in `America/New_York` (`septa_api.TIMEZONE`).

### `load_catalog()`

Returns the bundled `Catalog`: `routes` by route ID, `stops` (stop ID to name), and the `gtfs_version` it was built from. It reads a file, so call it in an executor from async code. The result is cached.

A route's `directions` carry each direction's GTFS `id`, `name` (`Northbound`, `Inbound`, ...), `destination`, and ordered `stop_ids`. Direction IDs mean different things on different routes, so match on `name`.

### `SeptaClient(session)`

Takes an `aiohttp.ClientSession`, which the caller owns.

### `await client.async_get_alerts()`

Every active and upcoming `Alert` across all modes. Route-level alerts list `route_ids` and apply to both directions. Trip cancellations list only `trip_ids`, which match `StopDeparture.trip_id`. Use `alert.is_active(now)` to filter by the alert's active periods.

### `await client.async_get_stop_departures(stop_id, route_id, results=20, cancelled_trip_ids=())`

Upcoming `StopDeparture`s of one route from a bus, trolley, or subway stop, from the timetable. When a live vehicle is running the trip, `delay_minutes` and `vehicle_id` are filled in and `realtime` is `True`; `expected` is the scheduled time plus the delay. SEPTA caps `results` at 20.

The timetable still lists trips SEPTA has cancelled. Pass the `trip_ids` of `NO_SERVICE` alerts as `cancelled_trip_ids` and those departures come back with `cancelled` set to `True`, so they don't pass for a bus that's coming. Taking the IDs from the caller avoids fetching the alert feeds again for every stop.

### `await client.async_get_vehicles(route_id)`

Live `Vehicle` positions on a bus or trolley route. `direction` matches the catalog's direction names case-insensitively. Empty for subway lines.

### `await client.async_get_station_departures(station, results=5, cancelled_trains=None)`

A Regional Rail station's live departure board, as `TrainDeparture`s, `results` per direction. `direction` is `N` or `S` (SEPTA's through-Center-City convention), not inbound/outbound.

### `await client.async_get_next_to_arrive(origin, destination, results=5, cancelled_trains=None)`

The next Regional Rail `Trip`s between two stations, each with one or two `TripLeg`s and the `connection_station` if there's a transfer.

Station arguments are catalog stop names; the client translates them to the legacy names SEPTA's JSON API expects. Station names in the results (`origin`, `connection_station`, ...) are SEPTA's legacy names.

### `cancelled_trains(alerts)`

SEPTA lists cancelled Regional Rail trains as on time. This maps the train numbers that alerts say are cancelled to `None` (the whole train) or the alert's text (part of its run). Pass it as `cancelled_trains` to either rail method: wholly cancelled `TrainDeparture`s and `TripLeg`s come back with `cancelled` set to `True`, partly cancelled ones with `cancelled` left `False` and the alert text in `cancellation_note`.

```python
now = datetime.now(TIMEZONE)
alerts = [a for a in await client.async_get_alerts() if a.is_active(now)]
trips = await client.async_get_next_to_arrive(
    "Doylestown", "Suburban Station", cancelled_trains=cancelled_trains(alerts)
)
```

Filter by `is_active()` first: train numbers repeat daily, so an expired alert would otherwise flag the same train on a later day.

Rail cancellations come either as structured trip alerts or only as alert text ("Inbound train #5319 ... is canceled ..."), and the text match follows SEPTA's current wording. Partial cancellations aren't flagged because the same train really does run on the rest of its route: on 2026-11-30, train 5319 "canceled to Suburban Station" skipped Doylestown to Suburban but ran on to Wawa, so flagging it would have been wrong at Media and Wawa. Show `cancellation_note` so riders at the affected stations still see the warning.

### Exceptions

- `SeptaRequestError`: SEPTA rejected the request, e.g. an unknown station or stop.
- `SeptaConnectionError`: SEPTA couldn't be reached or returned a server error.
- `SeptaError`: base class; also raised for malformed responses.

## License

MIT
