aiomobilitydatabase
Async Python client for the Mobility Database — the catalog MobilityData stewards of GTFS, GTFS Realtime, and GBFS feeds from transit agencies and bike/scooter share systems around the world.
The core package wraps the catalog's
REST API
with a fully typed asyncio client: search feeds, look up their metadata, find the
hosted dataset URL. The feeds layer goes one step further and consumes
the actual transit/bike-share data those feeds point to — scheduled and live
arrivals, origin→destination trip queries, vehicle positions, service alerts,
GBFS stations and vehicles — giving you a feed ID (or a plain feed URL) in and
typed snapshots out.
Installation
pip install aiomobilitydatabase
That installs the catalog client and GBFS feeds. To also consume GTFS
schedules and GTFS-RT, install the feeds extra, which pulls in
gtfs-realtime-bindings for
protobuf parsing:
pip install aiomobilitydatabase[feeds]
Using TransitFeedHandle or MobilityFeedsClient.get_transit_feed* without
the extra raises an ImportError telling you to install it. This is fail-loud
by design: without the extra, from aiomobilitydatabase.feeds import * and
hasattr(feeds, "TransitFeedHandle") raise that ImportError too.
Requires Python 3.12+.
Authentication
Sign up at mobilitydatabase.org and copy your
refresh token from the account page. The client exchanges it for short-lived
access tokens automatically (including proactive refresh before expiry). Both
MobilityDatabaseClient and MobilityFeedsClient take the same refresh token —
the feeds client wraps a catalog client internally and shares its authentication.
The token is only required for catalog operations: MobilityFeedsClient's
direct-URL methods work without one.
Quick start — catalog
import asyncio
from aiomobilitydatabase import DataType, MobilityDatabaseClient
async def main() -> None:
async with MobilityDatabaseClient("YOUR_REFRESH_TOKEN") as client:
# Free-text search across feed name, provider, and location
results = await client.search_feeds(
search_query="new york", data_types=[DataType.GTFS_RT], limit=10
)
found = results.results or () # None when the API sends no list
for item in found:
print(item.id, item.provider, item.status)
# Full detail for one feed, including the producer URL
feed = await client.get_gtfs_rt_feed(found[0].id)
assert feed.source_info is not None
print(feed.source_info.producer_url)
asyncio.run(main())
Every catalog endpoint has a method, its filters as keyword arguments. Per
GTFS feed there is the dataset list, availability checks, the Seal of
Reliability with each criterion's state (get_gtfs_feed_reliability()),
each dataset's service coverage (get_gtfs_feed_continuous_coverage()), and
validation report history (get_gtfs_feed_validation_reports(), whose
severities filter narrows each report's notices).
A GtfsFeed and a search result carry the feed's Seal of Reliability in
brief (reliability_seal) and whether it is seasonal;
search_feeds(has_seal=True) filters on the seal. As in the API, a
GbfsFeed is a BasicFeed: it has no status, official flag, name, note or
related links.
Quick start — feeds
MobilityFeedsClient resolves a feed ID (GTFS, GTFS-RT, or GBFS) into a handle
that fetches and caches the actual data. GBFS needs no extra; GTFS and GTFS-RT
(get_transit_feed*) require pip install aiomobilitydatabase[feeds].
import asyncio
from datetime import UTC, datetime
from aiomobilitydatabase.feeds import (
ArrivalsQuery,
Circle,
MobilityFeedsClient,
TripQuery,
)
async def main() -> None:
async with MobilityFeedsClient(
"YOUR_REFRESH_TOKEN", cache_dir="/path/to/cache"
) as client:
# The full catalog client is available via .catalog:
results = await client.catalog.search_feeds(search_query="portland", limit=5)
for item in results.results or ():
print(item.id, item.provider, item.data_type)
# Transit: accepts a GTFS or GTFS-RT feed ID; resolves the sibling.
# api_key authenticates with the PRODUCER (distinct from your catalog
# refresh token); on_progress reports download/index build progress
# for the first (uncached) fetch of a feed's static dataset.
# (p.fraction is None when the server doesn't announce a total.)
transit = await client.get_transit_feed(
"mdb-100",
api_key="PRODUCER_API_KEY",
on_progress=lambda p: print(p.phase, p.fraction),
)
# Picker-style helpers: stops in a zone, routes serving a stop.
# stations_in collapses GTFS station hierarchies (platforms group
# under their parent station, entrances are dropped) for clean UIs.
home = Circle(latitude=45.52, longitude=-122.68, radius_m=800)
stations = transit.stations_in(home)
nearby_stops = transit.stops_in(home)
routes = await transit.get_routes_serving(stations[0].stop_ids[0])
# Scheduled arrivals merged with realtime (delays, cancellations,
# new and replacement trips) when the feed publishes TripUpdates.
# Pass several ArrivalsQuery objects to get several boards (each
# with its own stops, route/headsign filters, and limit) from one
# realtime fetch; the result has one list per query, in order.
# Delayed trips stay listed until their prediction passes. Boards
# are open-ended by default: each fills to its limit however far
# ahead the next departures are (pass end= to bound the window).
[arrivals] = await transit.get_arrivals(
[ArrivalsQuery([nearby_stops[0].id], limit=2)]
)
for arrival in arrivals:
# When it leaves, as the board orders it: predicted if known.
when = arrival.effective_departure
if arrival.canceled: # shown, so riders see it; it won't run
live = "cancelled"
else:
live = "live" if arrival.realtime else "scheduled"
# .stop and .route are the whole static records: platform codes,
# coordinates, route_type and route colours all come along.
route = arrival.route.display_name if arrival.route else arrival.route_id
print(f"{route} -> {arrival.headsign}: {when} ({live})")
# Origin→destination: the next departures from stop A on trips that
# later reach stop B, with the same realtime overlay. is_first/is_last
# flag the first/last such departure of the service day. Batched
# like get_arrivals: several stop pairs, one realtime fetch.
[trips] = await transit.get_upcoming_trips(
[TripQuery(nearby_stops[0].id, nearby_stops[1].id, limit=2)]
)
for trip in trips:
name = trip.route.display_name if trip.route else trip.route_id
# Cancelled journeys stay listed (and count toward limit).
print(name, trip.scheduled_departure, trip.is_last, trip.canceled)
vehicles = await transit.get_vehicles(zone=home)
alerts = await transit.get_alerts()
# GTFS-Flex on-demand service: the next windows a ride can be
# requested in around home, and whether each can still be booked.
for window in await transit.get_on_demand_windows(home, limit=3):
booking = window.pickup_booking # None: no rule, or not placeable
bookable = booking.is_open(datetime.now(UTC)) if booking else None
print(window.service.route_id, window.window_start, bookable)
# GBFS bike/scooter share:
bikes = await client.get_gbfs_feed("gbfs-300")
info = await bikes.get_system_info()
stations = await bikes.get_stations(zone=home)
free_vehicles = await bikes.get_vehicles(zone=home)
asyncio.run(main())
Direct URLs (no catalog account)
If you already know your feed URLs, you can skip the catalog — and the
refresh token — entirely. get_transit_feed_from_urls and
get_gbfs_feed_from_url return the exact same handle objects as the
catalog methods, so everything above works unchanged:
import asyncio
from aiomobilitydatabase.feeds import ArrivalsQuery, MobilityFeedsClient
async def main() -> None:
# No refresh token: only catalog operations need one.
async with MobilityFeedsClient(cache_dir="/path/to/cache") as client:
transit = await client.get_transit_feed_from_urls(
"https://agency.example/gtfs.zip",
trip_updates_urls=["https://agency.example/gtfs-rt/trip-updates.pb"],
vehicle_positions_urls=["https://agency.example/gtfs-rt/positions.pb"],
headers={"Authorization": "Bearer PRODUCER_TOKEN"}, # optional
)
[arrivals] = await transit.get_arrivals([ArrivalsQuery([transit.stops[0].id])])
bikes = await client.get_gbfs_feed_from_url(
"https://bikes.example/gbfs/gbfs.json"
)
stations = await bikes.get_stations()
asyncio.run(main())
Notes on direct mode:
- Catalog static datasets are served from the Mobility Database's own
storage; direct mode fetches your URL, with the optional
headersapplied to the static download and every GTFS-RT/GBFS fetch the handle makes. Like any aiohttp request headers they follow redirects, to another origin too, exceptAuthorization,CookieandProxy-Authorization, which go to the URL's own origin only -- also when a GBFS discovery document places an endpoint at another origin. - RT URLs are declared per layer (
trip_updates_urls,vehicle_positions_urls,service_alerts_urls), so each operation only fetches sources that can serve it. A combined feed listed under several layers is deduplicated and fetched once per operation; if you don't know a producer's layer split, pass the same URL to every layer. - Dataset identity comes from the download's own strong
ETaginstead of catalog dataset IDs (aHEADreporting the same one skips the download); a weakETag, aLast-Modified(never exact) or none at all falls back to hashing the downloaded bytes, sorefresh_static()still only rebuilds on real changes. Only a200or203is a dataset. The cache key is derived from the static URL (url-<hash>, exposed astransit.static_feed_idand accepted bypurge_cache()), andtransit.static_datasetisNone(there is no catalog metadata). - Accessing
client.catalog(or any catalog-backed method) on a tokenless client raisesMobilityDatabaseError.
How it works
- Scheduled arrivals for every feed: the hosted GTFS zip is indexed into
SQLite (agencies, stops, routes, trips, stop_times, calendars, frequencies,
feed_info) in a worker thread — the event loop is never blocked. Arrivals
work with or without realtime coverage; GTFS-RT TripUpdates overlay delays,
cancellations, deletions and realtime-only trips when present.
NEW (or ADDED) trips and REPLACEMENT runs show at their stops and as
origin→destination journeys, at the times their updates give; a
replacement hides the scheduled run it replaces. One extra trip per
trip_id is shown, the last sent -- but an ADDED sharing its id with a NEW
trip or a DUPLICATED's original or copy is ignored, as the
ADDED-to-DUPLICATED migration guide says. A DUPLICATED trip shows
as a copy of its original, under the copy's own trip id, moved to the
copy's start date and time, with its updates predicting against that
schedule (one whose updates state
scheduled_timeis shown by those updates alone, as a NEW trip is); the original is untouched. A trip whose frequencies.txt service is headway-based (exact_times0 or empty) "cannot be duplicated", and such a copy is ignored. A cancelled run stays listed at its scheduled time withcanceled=Trueand no prediction (boards and journeys alike, counting towardlimit), so riders see the cancellation; a deleted one "must not be shown to users" and is gone. Either always wins over stale predictions, and a deletion over a cancellation. - Arrivals are batched and delay-aware:
get_arrivals()takes a sequence ofArrivalsQueryand returns one board per query from a single schedule read and a single realtime fetch, so several stops with different route/headsign filters cost one round trip instead of one each. Each query's filters apply before itslimit, andlimitcaps that board as a whole rather than per GTFS stop — so a narrow filter can never come back empty because busier routes used up the limit. Agracewindow (default one hour) keeps a delayed trip listed past its scheduled time until its prediction passes, while a schedule-only departure still drops at its scheduled time. - One time window everywhere, open-ended by default: every dated query
takes
start(default now),endand a limit. Withend=Nonea board fills to its limit however far ahead the departures are — overnight, over a weekend, past a holiday — instead of going empty after the last bus. Every dated query reads the schedule in doubling slices (2h, 4h, 8h, ...), each pass reading only the new slice for boards still filling, with route and headsign filters applied in SQL; a limited board stops as soon as it is settled, bounded or not. A board stops scanning once nothing more can match: past the last day any service that serves its stops, routes and headsigns runs — so a filter matching nothing, a seasonal route, or a calendar running "forever" all end promptly. Realtime is fetched once, and the runs it can move — the ones a TripUpdate addresses and the ones a detour rebuilds (on theservice_datesit must name) — are read whole before the scan begins; every other row sorts at its scheduled time, so a board is final as soon as it is full inside the slice read so far, and the answer is exactly that of reading the whole window. Each slice looks back exactly as far as the feed's departures reach past their service day (a night service at 47:30, a multi-day trip at 60:00), whatever the zone's clocks do, and never before its first service day; a departure four or more days past its day is placed on its own instead of dragging every scan back. Times count from "noon minus 12h" of the service day, in elapsed time as GTFS specifies, so on a DST-change day they are off local midnight by the size of the jump. An open-ended query with no limit raisesValueError, as do a naive (timezone-less) or unrepresentablestart/end, a window opening where service days can't be dated (start - gracebefore 0001-01-03 00:00 UTC, orstartat or after 9999-12-01 00:00 UTC), and a negativegrace.endbounds scheduled times (a realtime-only trip'sscheduled_time, or its predicted time where it gives none); a delayed trip predicted past it still shows. - Producers decide how fresh is fresh: realtime and GBFS fetches
follow HTTP caching strictly (RFC 9111, as a private cache). Inside a
response's declared lifetime (
Cache-Control: max-age, orExpires/Date, less itsAge) the stored parse is reused with no request; afterwards the request is conditional (ETag/Last-Modified), so an unchanged feed costs a304. A304counts only if its validator identifies the stored copy; one naming anotherETag, or none at all, changes nothing and is asked again unconditionally. Validators must be well-formed: an unquotedETag(abc123, a common misconfiguration),*or a list, and aLast-Modifiedthat isn't an HTTP-date, validate nothing — such a producer gets unconditional requests. A counting304updates only the headers it carries — one with just itsETagafterno-cacheis stillno-cache; one withoutDateis dated on arrival; one withoutAgekeeps the storedAge— and freshness is recomputed from the merged headers. A stored copy answers only requests matching the request headers itsVarynames: a cookie the producer set since, or a changed session default header, means asking again (a304then makes it the answer for the new request);Vary: *is never stored, and a session with client middlewares can add headers no prediction sees, so for such a session every response with aVaryis revalidated. A redirected response answers its original URL only while every redirect may be reused too: the shortest lifetime of the chain, none when a redirect declares none. A 302, 303 or 307 without freshness of its own is asked every time, even underrt_min_interval. A redirect's ownVarycounts: the first redirect's is matched against the original request, while later hops and the target can only be shown to match on aiohttp's automatic headers — so aVary: Accept-Encodingstill lets a redirected feed be reused. Validators go only to the resource they came from: a redirected feed's original URL is asked plainly and its target conditionally, and a304from any other resource is asked again unconditionally. Only a200(or203) carries a feed: any other status below 400 is aSourceConnectionError, never an empty feed stored in its place. A handle's ownCache-Control: no-storerequest header keeps responses out of the cache; the other request directives are advisory (RFC 9111 section 5.2.1) and ignored. A bareno-cacherevalidates every time (one naming fields only bars passing those fields on, which this cache never does),no-storeis never stored, invalid freshness (including a malformedCache-Control) counts as stale, and a response declaring nothing is revalidated on every call — no heuristic lifetimes. A GBFS document'sttlcounts from its ownlast_updated, and the shorter ofttland the HTTP lifetime wins — on a304too, so a renewal never outlives the document; an unusablettl, or one without a usablelast_updatedto count from, means the document isn't reused. A direct-URL handle'sgbfs.jsonis no exception: once itsttllapses it is read again, so endpoints the system moves are followed. Concurrent calls share one in-flight request per URL and request headers until it is sent (a cancelled caller cancels neither it nor the other waiters); a call arriving later waits for it and checks the store, so it never gets a response it may not reuse. Requests for one URL run one at a time, each checking the store first. A full response always replaces the stored one, as RFC 9111 requires — even an edge's older snapshot (by GTFS-RT header timestamp or GBFSlast_updated).rt_min_interval=onget_transit_feed*is an opt-in request budget for producers that declare no freshness at all: it reuses a realtime parse younger than the interval, and never extendsno-cache,max-age=0, an expired lifetime,no-storeor aVarymismatch. - Date-less realtime means the current run: a TripUpdate, cancellation
or vehicle with no
start_dateapplies to one run, judged at its own feed's header timestamp alone (never a query setting, nor another feed's timestamp): the run scheduled to be under way (including last night's past-midnight run, and one already under way when a spring-forward day starts the evening before its date); else the run nearest in time, up to today — a morning update reaches the afternoon's run, and a late-running run keeps its updates past midnight — never tomorrow's, however wide the window or late the board'sstart. Two runs equally near (two under way at once) take neither. GTFS-RT requiresstart_datefor a trip lasting more than a day (first departure to last arrival) and bothstart_dateandstart_timefor a frequencies.txt trip, so a date-less update or vehicle for either applies to no run — nor does a frequency vehicle missing itsstart_time, nor an update for a trip whose times decrease (arriving before it departs). A dated one applies to exactly its day. A NEW (or ADDED) trip's vehicle -- and a DUPLICATED copy's, by its own trip id -- is the one its update names by vehicle id, else the single position naming its trip_id -- an id the schedule does not use -- whatever day it names (two such positions: none). - frequencies.txt is materialized at build time: headway-based trips
(common for metro/BRT) expand into concrete repetitions under synthetic
{trip_id}#{start_secs}ids, so every schedule query — arrivals, origin→destination, routes-serving — sees them as ordinary trips. Each repetition departs its first stop at its start, asstart_timedefines it. Service withexact_times0 (or empty) "does not follow a fixed schedule", so its repetitions reporttimepoint_exact=False, and realtime names its runs by astart_timethat "may be arbitrary": a run is the trip moved to that start (and detoured as any run of the trip is), shown under its own{trip_id}#{start_secs}id in place of the repetition whose headway slot holds it -- one headway from that repetition's start, never past the trip's next repetition. Two runs in one slot both show. Only its updates' times predict it ("Delay can only be used in case the trip update refers to a scheduled GTFS trip, as opposed to a frequency-based trip"), and nodelay_secondsis reported against a schedule such service does not keep. A cancellation, deletion or replacement of such a run is one of its slot's repetition: the slot's running and replacing runs are shown in its place, and only with none is the repetition itself shown cancelled (or, if any run in the slot is deleted, not at all). A run's vehicle is the one naming its own start; a vehicle alone, with no update for its run, adds no run. A start in no slot, or on a day the trip does not run, names no run. - Schedule data means what GTFS says it means: stop times are in
agency.txt's
agency_timezone(a catalog's zone is only a fallback for a dataset naming no usable one). A call timed by only its arrival or only its departure arrives and departs at that time. An origin→destination trip is offered only where the rider can board and alight, never from a call with no pickup or to one with no drop-off. Headsign filters andget_headsigns_serving()use the headsign shown at the stop: itsstop_headsignwhere set, else the trip's. A stop under a parent station takes the station'sstop_timezone, and itswheelchair_boardingwhen its own is 0 or empty.stations_in()groups stops byparent_stationalone: two stops that only share a name stay apart. - Spec-correct realtime matching: GTFS-RT updates are matched by
(trip_id, start_date, start_time), so an update addresses exactly one run of a frequency trip (anexact_times1 repetition by its own start; see above for headway-based service) and exactly one service-day instance (a plain trip'sstart_time, when given, is its first departure, as GTFS-RT requires; any other value names no run) — a "trip X is canceled tomorrow" posting never cancels today's run. An update without atrip_idnames the one trip itsroute_id,direction_id,start_time(the first departure) andstart_dateresolve to, if exactly one non-frequency trip matches. A cancellation or deletion of a run wins over any prediction for it; of several predictions for one run, the one naming its date wins over one leaving it to the feed's time, and one omitting a plain trip's own start time over one spelling it out; then the later feed. A StopTimeUpdate predicts the events (arrival, departure) it gives by their own time, else their own delay — an event it does not give is not predicted — and its delay (a time, when given, against the schedule: "time will take precedence") propagates to subsequent stops until newer information. The trip-level delay covers stops until the first update that states a delay or isNO_DATA; after that, every update except aSKIPPEDone replaces the delay carried from earlier stops, so one stating none leaves later stops without one.NO_DATAcuts propagation: that stop and every later one are schedule-only until an update states a delay.SKIPPEDsuppresses its stop (and any origin→destination row boarding or alighting there) and leaves propagation alone. A stop whose departure realtime does not predict stays listed until its predicted arrival, if that is later. An update naming a stop bystop_idalone on a trip that visits it twice names no stop (the spec requiresstop_sequencethere), and one whosestop_sequenceandstop_iddisagree names none either, unless thestop_idis the update's ownassigned_stop_id. - Rows carry whole records, not copied columns:
StopArrival,UpcomingTrip, andVehiclePositioneach expose the fullStopandRoutethey refer to, so platform codes, coordinates, route colours androute_typeare reachable without a second lookup — useroute.display_name/stop.namefor the human-readable strings. The rawstop_id/route_idstay alongside, since those are what feeds reference and what filters key on; aroute_idnaming a route absent fromroutes.txtleavesrouteasNonerather than inventing one. - Vehicle positions name their trip instance:
VehiclePositioncarries the parsedtrip_start_date/trip_start_time, the pair a GTFS-RTTripDescriptoruses to address one run (the start time atimedeltasince the start of the service day, as every GTFS time is here). That is what lets two buses out on the same headway-based trip be told apart — without it, concurrent repetitions of one template trip are indistinguishable. A vehicle that reports no position is still returned, withlatitude/longitudeofNone(as a docked GBFS vehicle's are), and no zone includes it. Any vehicle'scurrent_statusisNonewithout acurrent_stop_sequence(the spec ignores it then), and itstimestampfalls back to the message's when it sends none. - Realtime accessibility wins: a row's
wheelchair_accessibleis what itsTripUpdate'sVehicleDescriptorstates, and the static value where it states none. It reads the same with or withoutwith_vehicles; an attachedVehiclePositioncarries its own descriptor's value. - Everything the library hands out is immutable: every model (catalog
and feeds) is a frozen dataclass whose collections are tuples or
read-only dicts, and a handle's
stops/routes/agencies/rt_feedsare tuples. Shared state can't be changed from outside, and every model is hashable. The read-only dicts are realdictsubclasses, so models still work withdataclasses.asdict,copy.deepcopy,pickleand JSON encoders. Query results (get_arrivals()and friends) are fresh lists the caller owns. - The full descriptive surface is exposed, typed by shape: closed GTFS
vocabularies are enums (
WheelchairAccess,BikesAllowed,PickupDropOffType,StopLocationType, alert cause/effect/severity, vehicle status/congestion/occupancy),timepointis a bool with the spec's absent-means-exact default, and open vocabularies (route_type,direction_id) stay raw ints. A blank or absent cell takes the value GTFS gives "empty" where it defines one (a regular pickup, a stop or platform, no accessibility information, black-on-white route colours). Out-of-vocabulary values degrade toNone, so descriptive metadata never fails a build. Consumers decide what to keep. - Numbers are ASCII-strict, and strictness follows the field's role: a
GTFS number must be plain ASCII digits, so a Unicode decimal (
٨), a sign prefix, or Python's1_0underscore grouping is never quietly reinterpreted as a plausible value. A malformed structural cell —stop_timestimes,stop_sequence,headway_secs,exception_type, calendar weekday flags — fails the build, because a wrong departure time or a wrong call order is worse than no feed at all. So does a trip repeating astop_sequence(fixed or GTFS-Flex calls alike), which GTFS requires to increase along the trip, and a trip intrips.txtnamed like one of a frequency trip's{trip_id}#{start_secs}repetitions. A malformed descriptive cell still degrades toNone. - Detours are applied, not annotated: a GTFS-RT
TripModificationsentity REPLACES a span of a trip's calls, so a board that ignored it would keep showing departures at stops the vehicle no longer serves, and would misspropagated_modification_delayon every stop after the detour. Boards and journeys alike show the run as rebuilt ("as if the static GTFS would have been modified"): the same trip, service and block, its rows realtime. Replacement times are measured from the reference stop the spec names, a replacement stop may be defined only by an RTStopentity and takes stop_times' defaults (regular pickup and drop-off, exact times), and a detour that routes a trip through a stop its static schedule never served shows up there. A modification replacing no stop (no end selector) inserts its stops before its start stop; one changing only the shape delays the stops after it. Delays of several modifications accumulate. The trip's own TripUpdates still apply, resolved against its schedule before the detour: they predict the stops it keeps (a skipped one is not served, a cancelled run is not rebuilt), withdelay_secondsonly where the detour left the schedule alone, and "no ETA would be available at the replacement stops". An entity listingstart_timesdetours only the runs they name -- a plain trip's start is its first departure -- and none if none parses. A replacement stop withouttravel_time_to_stopis left out rather than given an interpolated time. Rebuilt journeys, like every realtime-only trip's, are neitheris_firstnoris_last. - Schedule only, never the network:
get_scheduled_departures()is the schedule-only twin ofget_arrivals()— sameArrivalsQuerybatch, same window rules, no realtime and no grace. It makes no network request, so a calendar view or config flow keeps working when a producer's realtime endpoint is down. For every departure in a range, passendandlimit=None. - Service calendars are answerable:
get_services_on(date)returns the service ids running on a GTFS service date —calendar.txtresolved againstcalendar_datesexceptions, removals winning when a producer lists both types for one date — and every row carries itsservice_id, so "does this trip run next Tuesday" needs no second arrivals query. - GBFS ids resolve:
get_vehicle_types(),get_pricing_plans(),get_regions(), andget_alerts()turn thevehicle_type_id,pricing_plan_id, andregion_idon stations and vehicles into records. These documents are optional in GBFS (vehicle_typesonly conditionally required), so an unpublished one — or a listed one answering404, which GBFS says is not an error — is[]. A vehicle type'sform_factor/propulsion_typeand an alert'stypeare enums, as the GTFS-RT vocabularies are: a value newer than this library isNone, and its field is named in the record'sunreadable_fields, soNonealone means the document left the field out. An alert hasapplies_to(station_id=..., region_id=...)(no stations or regions listed: the whole system) andis_active(at), shaped like a GTFS-RT alert's. - Static metadata accessors:
transit.agencies,transit.feed_info(publisher, version, validity dates — useful for staleness checks), andget_headsigns_serving()alongside the stop/route helpers. - GTFS-Flex records:
transit.flex_locations(zones fromlocations.geojson, each aFlexLocationofFlexPolygons in(latitude, longitude), holes kept),transit.location_groups(stop groups with theirstop_ids), andtransit.booking_rules(everybooking_rules.txtcolumn;BookingTypeforbooking_type). A Feature without an id, or with a geometry that is not a well-formed Polygon or MultiPolygon (a position past ±90/±180 as written counts, as for stops), is skipped whole -- including a polygon that is not valid as GTFS-Flex requires (OGC Simple Features 6.1.11): a ring crossing itself or another, a hole outside its exterior or overlapping another hole, or holes touching the exterior and each other so as to cut the zone in two. Alocations.geojsonthat is not a GeoJSON FeatureCollection fails the build. - On-demand service in a zone:
locations_in(zone)picks the Flex zones aCircleoverlaps (its centre inside one, or the zone's edge within the radius; GeoJSON edges are straight lines in longitude and latitude, scaled to metres around the circle), andawait get_on_demand_services(zone, route_ids=...)lists everyOnDemandServiceserving it: a call at a zone it overlaps, at a stop group with a stop in it, or at a stop in it served within a window. Each carries its trip, route,service_id, itsstart_pickup_drop_off_window/end_pickup_drop_off_windowastimedeltaoffsets into the service day (None where unknown, never "no limit"),exact_times(True on a plain trip or anexact_times=1repetition; False on a headway-based one, whose windows are approximate; None when frequencies.txt's value is unparseable, or for a frequencies.txt trip with no timed call to repeat from, kept as one trip, its windows unknown), pickup/drop-off types, and each id it names beside its record (an id whose record the feed lacks keeps the id, with None for the record). Schedule only, no network. Meant for circles of up to a few hundred kilometres that do not reach a pole, likestops_in. - On-demand windows on dates, with booking:
await get_on_demand_windows(zone, start=..., end=..., limit=..., route_ids=...)places each of those calls on every GTFS service date its trip runs, as anOnDemandWindow(window_start/window_endinstants, measured from noon minus 12 hours like every GTFS time), where the window overlaps[start, end]-- one under way atstartcounts. Same time rules asget_scheduled_departures(): open-ended by default, an open-ended query needs alimit; sorted by window start. A call whose window is unknown, ends before it starts, or ends past year 9999 once placed on a date (garbage) has no dated window.pickup_booking/drop_off_bookingplace the call's booking rules on the window as aBookingWindow(earliest,latest,is_open(at)): real-time booking up to the window's end; same-day booking fromprior_notice_duration_maxbefore its start (or a start day) toprior_notice_duration_minbefore its end; prior-day booking byprior_notice_last_timeon theprior_notice_last_day-th day before the service date, counting the daysprior_notice_service_idruns where given. Eachbooking_typereads only the columns the spec allows it; a forbidden one is ignored.earliestis None only where the rule sets no earliest time, and a rule that cannot be placed gives None, never a guessed window: a field it needs missing, a column it reads that the file states but that can't be read (BookingRule.unreadable_fields), a duration max under the min, booking that for this window opens only after it closes or closes after the window it is "before", or a day count that does not end within a year. - Alert scope is the spec's, selector by selector:
ServiceAlertkeeps eachinformed_entitywhole as anEntitySelector(spec field names; a trip as aTripSelector, one run of it where it gives a start date or time). A selector's fields are joined by AND, soapplies_to(stop_id="S", route_id="R")is true for an alert on route R at stop S, andapplies_to(stop_id="S")is not. Theagency_ids,route_ids, ... lists only index the values named.is_active(at)counts a period from its start up to, not including, its end. Text fields pick English (en-UScounts), else a translation without a language, else the first; an unset cause, effect or severity is the spec's UNKNOWN default. - Boards and journeys can carry their alerts:
with_alerts=Trueonget_arrivals()andget_upcoming_trips()(shaped likewith_vehicles) fills each row'salertswith the alerts that apply to it. The library matches them against the row's run, which a caller cannot see: the trip, the repetition's start (or a plain trip's first departure), and the service day, as well as the route, agency, direction and stop. An alert's trip names its run as a TripUpdate's does: without a trip_id, the one trip its route, direction and start resolve to; without a date, the run a plain trip's trip_id names at the alert feed's time. A station's alerts reach its platforms. Every alert is kept whatever its period;is_active(at)says which apply now. - GBFS exposes what the documents carry: the full station surface
(
is_installedalongsideis_renting/is_returning— a station removed from the street is not "operational"; disabled counts, address, region, virtual-station flag), vehicle docking and fuel state (a vehicle docked at a station need not report a position: its coordinates areNone, and a zone places it at its station), and aGbfsSystemInfowith the operator's contact, licensing, and terms URLs. A flag (is_renting,is_installed, ...) is JSONtrue/false, or1/0; any other value isNone(unknown), neverTrue.last_reportedis exposed on both stations and vehicles so you can tell fresh data from stale, and is parsed from either GBFS 2.x POSIX seconds or 3.0 RFC 3339 (whose offset is required: without one, a timestamp isNone). Plusrental_urisdeep links and TTL-based document caching. cache_dirstrongly recommended: the static index is cached on disk keyed by feed, validated against the dataset ID, so restarts are instant and rebuilds only happen when the agency publishes a new dataset (await transit.refresh_static()— call it daily; it swaps in the new index only after it's built, so lookups never see a half-built database, and it is safe to call while queries are in flight: the swap waits for in-flight reads to finish, and two overlapping refreshes run back to back rather than double-building). A corrupt or unreadable cache is treated as a cache miss and rebuilt rather than raising: as a cached index is opened, SQLite checks every page (PRAGMA quick_check) and its schema is compared with the library's, so one damaged page anywhere is a miss. That check reads pages, not the values in them; the stops, routes, agencies, feed info and Flex records a handle holds are read as it opens, so a damaged value among them (one that no longer decodes, say) is a miss too. Damage met later by a query (such a value elsewhere, or a file changed after it was opened) isFeedParseError;purge_cache()rebuilds it. Without acache_dirthe index is built in memory on every startup.- Pull, not push:
TransitFeedHandle/GbfsFeedHandlereturn snapshots on demand — there's no built-in polling loop or scheduler. Bring your own (e.g. Home Assistant'sDataUpdateCoordinator). purge_cache()deletes a feed's cached static data (or all feeds' when called with no argument) — call it on cleanup/removal of a configured feed. Afeed_idthat is not a bare child name of the cache directory raisesValueErrorinstead of deleting anything, so an absolute path, a..component, a symlinked entry, or a degenerate""/"."cannot take out every feed's cache. Purging a feed with no cache directory is a no-op, so repeated calls are idempotent.transit.close()releases a handle's SQLite connection — call it when you are done with a handle; the client'sclose()does not do it for you. It is safe with queries in flight, cancelled ones included: a read already running on a worker thread finishes first, and any read asked for afterclose()raisessqlite3.ProgrammingError.- Producer authentication: pass
api_key=toget_transit_feed(); it is applied per the catalog'sauthentication_type(query parameter or header) — distinct from the refresh token used to authenticate with the catalog itself. The one key goes to every GTFS-RT feed the catalog links to the handle and marks as needing authentication, at each feed's own origin -- which can be another vendor's than the agency's that issued the key, as the catalog lists them. A redirect never carries a header key to another origin: from the first redirect that leaves the feed's origin on, it is left off, along with credentials in the URL. (A session carrying credentials of its own, which couldn't be left off, is refused when the handle is made; see below.) - Zones are circles (matching Home Assistant zone entities); GBFS vehicle filtering happens client-side because GBFS feeds are full-system dumps by design, with no server-side geo-query.
- Timestamps are tz-aware UTC throughout the feeds layer.
What this does not expose
Deliberate omissions, so you can tell "not supported" from "not found yet".
GTFS files not ingested. The static index reads agency.txt, stops.txt,
routes.txt, trips.txt, stop_times.txt, calendar.txt,
calendar_dates.txt, frequencies.txt, feed_info.txt, and the GTFS-Flex
files (locations.geojson, location_groups.txt, location_group_stops.txt,
booking_rules.txt). Everything else in the zip is ignored:
shapes.txt— route geometry. Nothing here draws a line on a map, so trips carry noshape_id.transfers.txt— no transfer rules, minimum transfer times, or trip-to-trip continuations, and no journey planning across a transfer.pathways.txt/levels.txt— no in-station walking graph.fare_attributes.txt/fare_rules.txtand all GTFS-Fares v2 files — no fares, zone pricing, or rider categories. (Stop.zone_idis exposed as a raw cell, but nothing interprets it.)translations.txt— text is returned as the feed wrote it.
GTFS-Flex: no on-demand trip planning or realtime. Which on-demand
calls serve a place, their dated windows and when each can be booked are
answerable (see On-demand windows on dates, with booking); journeys that
mix fixed and on-demand legs, and where a ride picked up in one zone can
be dropped off, are not, and on-demand windows are schedule only (no
realtime overlay). A zone-only feed loads
(stops.txt is optional when locations.geojson is present), and a
stop_times.txt row naming a zone, a stop group, or a pickup/drop-off
window is kept apart from the fixed calls: boards and
journeys show only the fixed calls around it, while a GTFS-RT update or a
detour naming its stop_sequence still applies at its place in the trip (a
delay stated there propagates to the fixed stops after it).
Service calendars are answerable — get_services_on(date) resolves
calendar.txt against calendar_dates exceptions, and rows carry their
service_id — but the raw weekday pattern and validity range behind a
service are not exposed as a model. get_scheduled_departures() with an
end and limit=None covers the range query a calendar view needs.
GTFS-RT: trip shapes. The RT shape entity (a detour's new geometry) is
not read, for the same reason shapes.txt is not: nothing here draws a line
on a map. Detours themselves ARE applied — see Detours are applied, not
annotated — and the stop entities they define are read.
GBFS endpoints not fetched. geofencing_zones, because it is GeoJSON
polygon geometry while zones here are deliberately circles — supporting it
means polygon containment, which is a geometry feature rather than another
document. And system_hours, which GBFS 3.0 removed in favour of
system_information.opening_hours (exposed as GbfsSystemInfo.opening_hours,
from get_system_info()).
Behaviour, not data. There is no polling loop or scheduler (see Pull, not push), no write access of any kind, and no cross-feed journey planning.
Error handling
All errors derive from MobilityDatabaseError. The catalog and feeds layers
each define their own subtree beneath it, so you can catch broadly
(MobilityDatabaseError) or narrowly per layer:
| Exception | Layer | Meaning |
|---|---|---|
MobilityDatabaseConnectionError |
catalog | Network failure, timeout, or invalid response body |
MobilityDatabaseAuthenticationError |
catalog | Invalid refresh token, or unauthorized after a token refresh |
MobilityDatabaseNotFoundError |
catalog | Resource not found (404) |
MobilityDatabaseRateLimitError |
catalog | Rate limited (429) |
MobilityDatabaseApiError |
catalog | Any other 4xx/5xx (carries .status and .body) |
MobilityFeedsError |
feeds | Base class for all feeds errors (subclasses MobilityDatabaseError) |
SourceConnectionError |
feeds | Producer/GBFS endpoint unreachable or errored (.status when HTTP, .url) |
SourceAuthenticationError |
feeds | Producer rejected the feed's api_key |
FeedParseError |
feeds | Undecodable protobuf (a string field that isn't UTF-8 included), malformed GBFS JSON or envelope, unreadable GTFS zip, a GTFS row with fewer fields than its header (or a filled one past it), a trip repeating a stop_sequence, a cached static index a query finds damaged, or a malformed scalar in a structural GTFS column (stop coordinates included, as is one outside WGS84's ±90/±180 as written -- 90.000000000000001 is past the pole, though its nearest double is 90) |
StaticDataUnavailableError |
feeds | Feed has no usable hosted static dataset (or, rarely and passingly, concurrent builds of another dataset kept replacing its index: retry later) |
The GBFS and GTFS-RT parse paths are total with respect to this table:
any producer document, however malformed, either returns a typed result or
raises one of the exceptions above — never a bare KeyError, TypeError,
ValueError or OverflowError from inside the library. So is the catalog
client: a 200 or 203 whose body isn't the documented JSON -- including a
value of the wrong JSON type, which is refused rather than converted -- is a
MobilityDatabaseConnectionError. The deliberate exceptions are caller
mistakes rather than feed problems, and raise builtins: purge_cache()
raises ValueError for a feed_id it will not accept (see above), and a
catalog method raises ValueError for an id of "", "." or "..", which
no URL can carry as one path segment (TypeError for an id that isn't a
str), or for a query value or license_url holding a lone surrogate (no
text a URL can carry), a float filter that is NaN or infinite, a datetime
filter without a timezone (RFC 3339 requires an offset; a naive time names
no instant), or a list item holding the comma the API separates items with.
A query
value of another type than the method takes (bytes, say, which would have
filtered on "b'...'") is a TypeError. Both are raised before any request
is made. A closed injected session is a RuntimeError.
get_matching_licenses() raises TypeError for a license_url that isn't a
str. MobilityDatabaseClient(...) raises TypeError for a refresh token that isn't
a str, and ValueError for an empty one; a request_timeout that isn't a
finite positive number (TypeError if it is no number at all); a base_url that isn't https (plain http only on loopback:
bearer tokens travel over TLS, RFC 6750) or holds credentials, a query or a
fragment; or an injected session with an auth, an Authorization, Cookie
or Proxy-Authorization default header, or a cookie set without a domain
(ClientSession(cookies=...)) -- any of which would ride on every request,
to every origin -- a base_url, or a default header outside the allowlist
(token names, visible-ASCII values).
Exception messages are written by the library alone: never a response body,
a URL's credentials or query, or another library's error text (any of which
can echo a token). A response's status and body are attributes
(MobilityDatabaseApiError.status/.body, and on
MobilityDatabaseAuthenticationError when the API answered) -- yours to log.
So does a feeds handle factory, for a caller input outside its allowlist:
headers= names must be tokens and their values visible ASCII, as must the
api_key; credentials in a URL you pass must be ones Basic auth can send
(Latin-1 without a control character, and no colon in the user-id), and an
Authorization header can't go beside them (a password alone counts).
An injected session may carry no credential -- no auth, no
Authorization, Cookie or Proxy-Authorization default, no cookie set
without a domain (ClientSession(cookies=...)) -- since it would
ride on every request, to every origin (pass credentials per request instead,
in headers=).
Exception messages are written by the library alone: never a URL, a response
body, or another library's error text, any of which can carry a credential.
SourceConnectionError and FeedParseError carry the URL asked for on
.url (without credentials, query or fragment), and the HTTP status on
.status. Every redirect is followed by the library, each target checked
like the first URL (a Location with a scheme of its own is taken as
written, RFC 3986 section 5.2.2, so http:///x names no host rather than
the current one); a hop to another origin sheds the request's credentials.
(Messages from a static build may quote the dataset's own cells: published
feed data, not anything sent or received over HTTP.)
Note the two independent auth flows: a MobilityDatabaseAuthenticationError
means your catalog refresh token is invalid; a SourceAuthenticationError
means the producer rejected the feed-specific api_key you passed to
get_transit_feed(). They fail independently and are never confused for one
another.
Session injection
With an externally managed session (e.g. Home Assistant's shared session), the
client never closes it. One shared session serves both catalog requests and
feeds fetches (GTFS-RT polls, GBFS documents, dataset zip downloads) when
passed to MobilityFeedsClient:
import asyncio
import aiohttp
from aiomobilitydatabase import MobilityDatabaseClient
async def main() -> None:
async with aiohttp.ClientSession() as session:
client = MobilityDatabaseClient("YOUR_REFRESH_TOKEN", session)
try:
metadata = await client.get_metadata()
finally:
await client.close() # session remains open; you own it
asyncio.run(main())
Testing methodology
The suite combines example-based, property-based, and conformance testing:
-
Example-based tests cover the catalog's endpoint methods and the feeds layer's client/transit/GBFS/static-index modules against a real
aiohttp.test_utils.TestServerrunning on loopback (tests/mock_server.py) — scripted per-(method, path)responses, with every request recorded for assertions on headers, query params, and bodies. This replaces aioresponses, which cannot construct mocked responses under aiohttp >=3.14. -
Property-based tests (
tests/feeds/test_properties.py, via Hypothesis) target the modules where correctness is a matter of an invariant holding across a wide input space rather than a handful of hand-picked cases:- the static-index date/time math (GTFS elapsed-seconds-since-service-day
arithmetic against a naive oracle, calendar/calendar_dates service-id
resolution, DST-transition handling) — this is where the original
hardcoded
±1 dayscan-window bug was found; - frequencies.txt materialization (arithmetic-progression oracles,
descriptor carry-through), GTFS-RT delay propagation (an independent
piecewise oracle over generated StopTimeUpdate sets, run against the pure
resolver at volume), and
start_date/start_timeinstance matching over windows containing two service-day instances of the same trip; - the circular-zone geometry (
in_circle's bbox prefilter is checked against the exact great-circle distance at generated boundary points); - GBFS field parsing (
_localized,_version_key, station/vehicle merging) and GTFS-RT protobuf parsing, both checked for totality — every generated input must produce a typed result or a documentedMobilityFeedsErrorsubclass, never an unhandled exception; - the batched arrivals contract: that batching is pure query factorization
(
get_arrivals([q1, q2])equals the two single-query calls), that a batch costs exactly one realtime fetch however many queries it carries, that route and headsign filters apply before the limit, and that every returned row's effective departure is still ahead ofnow; - the origin→destination query against an oracle built from the stored stop-call table: the self-join's direction rule (no return-trip rows) and the earliest-destination-call rule for loop trips, neither of which any test asserted before;
- window monotonicity — widening the window yields a prefix and widening
graceyields a superset — which guards the scan-window regression class directly, without a hand-built oracle; - open-ended equals bounded: for every dated query,
end=None, limit=kreturns exactly the firstkrows of the same query bounded beyond the end of service, read as a plain scan of the whole window — including with realtime delays, runs predicted hours early, garbage times, detours with several (or empty) modifications, dated and date-less cancellations, feed timestamps behind, ahead of or far from the query, and batches whose queries settle at different horizons; - GTFS-Flex: zone validity and circle overlap against exact references (rectangles, convex half-planes, holes, great-circle distance), Flex rows changing no fixed-route answer, every call serving a zone found and nothing else, dated on-demand windows against a brute-force calendar oracle across DST changes (so open-ended equals bounded there too), and booking deadlines against an independent count of service days;
- the cache as a round trip: a built index and the same index reopened from
disk answer every query identically, including the stored timezone, and
purge_cacheremoves exactly the named feed and nothing else for any generatedfeed_id; - error-contract fuzzing for malformed GTFS zips, RT payloads, and GBFS
documents (garbage bytes, wrong types, out-of-range values) — the
contract under test is "raises
FeedParseError/SourceConnectionError", not "does anything in particular with the garbage."
Hypothesis is a
devdependency and part of the default suite (no separate opt-in marker);.hypothesis/(its example database) is gitignored. - the static-index date/time math (GTFS elapsed-seconds-since-service-day
arithmetic against a naive oracle, calendar/calendar_dates service-id
resolution, DST-transition handling) — this is where the original
hardcoded
-
Conformance tests (
tests/feeds/test_sample_feed.py) run the index against Google's canonical GTFS sample feed — the feed the rest of the GTFS ecosystem validates against — with hand-computed expected schedules, frequency repetitions, and calendar exceptions pinned from the raw CSVs.
Development
uv sync --dev
uv run pytest
uv run ruff check . && uv run ruff format --check .
uv run mypy src
License
Metadata
Release files for aiomobilitydatabase 0.7.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| aiomobilitydatabase-0.7.1.tar.gz | 675.7 kB | With provenance | Details for aiomobilitydatabase-0.7.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| aiomobilitydatabase-0.7.1-py3-none-any.whl | Python 3 | none | any | Details for aiomobilitydatabase-0.7.1-py3-none-any.whl |
Total release size: 921.9 kB
Release files / aiomobilitydatabase-0.7.1.tar.gz
| Download URL | aiomobilitydatabase-0.7.1.tar.gz |
|---|---|
| Size | 675.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
b710eaa2a34e1bb4285e2f159ccef29ae4a177835fede0272dee2331947b542f
|
|
BLAKE2b-256 checksum How to use checksums |
8e90fb59c2f8f6c86768f07c44ffbbc1bfcafb6920d316d7bbadb2d2da714c35
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.
Transparency logRelease files / aiomobilitydatabase-0.7.1-py3-none-any.whl
| Download URL | aiomobilitydatabase-0.7.1-py3-none-any.whl |
|---|---|
| Size | 246.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
d3cc64d9f9900f42f7ca6d8fd93a58b83cf17699b2bb77b625d9639d418025da
|
|
BLAKE2b-256 checksum How to use checksums |
da7408c6b1d01b9aad51e2099b6cabf29b087a47bc00c2cc32fed137518b63ce
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.
Transparency logSecurity for aiomobilitydatabase 0.7.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for aiomobilitydatabase-0.7.1.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.