快速上手
安裝 tdx-tw、設定 API 金鑰並完成第一個查詢。
tdx-tw 是運輸資料流通服務平臺(TDX)的 Python SDK,負責認證、呼叫 API 與驗證回應,並把資料整理成 Python 物件。
安裝
需要 Python 3.13 以上版本。PyPI 套件名稱為 tdx-tw,匯入名稱為 tdx。
pip install tdx-tw 使用 uv 則執行 uv add tdx-tw。
選用功能
基本安裝已涵蓋所有查詢。下列功能需要額外套件,以 pip install "tdx-tw[polars]" 的形式安裝,未安裝時呼叫會引發 MissingDependencyError:
| 額外套件 | 提供的功能 |
|---|---|
tdx-tw[polars] | to_polars() 匯出 |
tdx-tw[pandas] | to_pandas() 匯出 |
tdx-tw[arrow] | to_arrow() 匯出 |
tdx-tw[geo] | Position.to_shapely() |
tdx-tw[geohash] | Position.to_geohash() |
tdx-tw[xml] | 以 pydantic-xml 模型解析 XML |
tdx-tw[mqtt] | 以 MQTT 接收推播 |
tdx-tw[gtfs] | 轉換為 GTFS Realtime |
tdx-tw[fast] | 以 pyproj 加速距離計算,未安裝時改用 GeographicLib |
tdx-tw[all] | 以上全部 |
API 金鑰
至
# macOS、Linux
export TDX_CLIENT_ID="Client ID"
export TDX_CLIENT_SECRET="Client Secret" # Windows PowerShell
$env:TDX_CLIENT_ID = "Client ID"
$env:TDX_CLIENT_SECRET = "Client Secret" 第一個查詢
列出公車路線各站的到站時間:
from tdx import Client
with Client() as client:
for board in client.bus_route("Taipei", "307").board():
print(board.route_name, board.direction)
for item in board.stops:
print(item.stop.name, item.estimate_seconds) 其他頁面的範例都省略建立用戶端的部分,直接使用 client。