Skip to main content

TDX

臺灣運輸資料流通服務平臺(TDX)的非官方 Python SDK。

CI 套件版本 Python 版本

繁體中文 | English

臺灣運輸資料流通服務平臺(TDX)匯集全臺公共運輸與道路資料。這個 SDK 負責認證、呼叫 API 與驗證回應,並把公車、軌道、自行車、停車、路況、航空、航運等資料整理成有型別的 Python 物件,同步與非同步皆可使用。

安裝

需要 Python 3.13 以上版本。PyPI 套件名稱為 tdx-tw,匯入名稱為 tdx。

pip install tdx-tw

使用 uv 則執行 uv add tdx-tw。選用功能以 extra 安裝,例如 pip install "tdx-tw[polars,geo]":

Extra 功能
polars 匯出為 Polars 表格
pandas 匯出為 pandas 表格
arrow 匯出為 Arrow 表格
geo 座標轉換為 Shapely 幾何物件
geohash 座標轉換為 geohash
fast 以 pyproj 加速距離計算
xml 將 XML 解析為 pydantic-xml 模型

設定 API 金鑰

至 TDX 註冊會員,在會員中心取得 API 金鑰的 Client ID 與 Client Secret。範例從環境變數讀取金鑰:

# 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"

快速開始

查詢公車路線各站的到站時間:

import os

from tdx import Client

with Client(os.environ["TDX_CLIENT_ID"], os.environ["TDX_CLIENT_SECRET"]) 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)

在同一個 with 區塊中,也可以查詢車站的列車,以及座標附近的自行車站:

from tdx import Position

for train in client.rail_station("TRA", "1000").trains():
    print(train.departure_time, train.destination, train.delay_minutes)

here = Position.at(longitude=121.517, latitude=25.047)
for place in client.nearby(here, city="Taipei", include=("bike",)).bike_stations:
    print(place.item.station.name, place.item.availability, place.distance)

非同步用戶端的操作相同,取得資料時加上 await:

import asyncio
import os

from tdx import AsyncClient


async def main() -> None:
    async with AsyncClient(
        os.environ["TDX_CLIENT_ID"], os.environ["TDX_CLIENT_SECRET"]
    ) as client:
        for station in await client.bike.stations("Taipei", limit=10):
            print(station.name, station.position)


asyncio.run(main())

縣市以 TDX 的英文名稱指定,例如 Taipei、NewTaipei、HsinchuCounty,可用 client.administration.cities() 查詢。

高階操作

Client 與 AsyncClient 提供下列操作,自動挑選端點版本並合併靜態與即時資料。非同步版本在取得資料時使用 await。

操作 內容
bus_route(city, name) 以完整路線名稱查詢站序、班表、線型、票價、車輛動態;board() 合併站序與到站預估
rail_station(system, station_id) 車站資料、出口、設施、列車、到另一站的班次與票價
bike_station(city, station_uid) 租借站點與即時借還數量
car_park(area, car_park_id) 路外停車場與即時空位
nearby(position, city=...) 座標附近的公車站牌、軌道車站、自行車站與停車場,依距離排序

nearby 每種資料需要一次以上請求,可用 include 只選擇需要的種類。

基礎服務

資料類別 查詢入口 主要功能
共通資料-行政區 administration 縣市、鄉鎮市區與村里
共通資料-公共運輸 transport_reference 主管機關、資料提供者、營運業者與行事曆
公車 bus 路線、站序、班表、票價、車輛動態與到站預估
軌道 rail 臺鐵、高鐵、捷運與阿里山林鐵的車站、班表、票價與即時資訊
自行車 bike 租借站點、即時借還數量與自行車道
停車資訊 parking 路外停車場、路邊路段、車格、即時空位與費率
共通資料-道路 road_reference 道路分類、路名、交流道與匝道
路況資訊 traffic 車流偵測器、資訊看板、攝影機、eTag 與即時路況
道路事件 road_events 公告與即時事件、交通管制及改道資訊
航空 air 機場、航班看板、班表、國內票價及 METAR
航運 ship 港口、航線、船班、票價、即時船位及到離港看板
GIS 圖資 gis 交通圖層、行政區界線、WKT、GeoJSON 與 XML
路段編碼 road_links 路段、路口、幾何及版本異動
充電樁 charging 站點、設備、費率與接頭即時狀態
觀光資訊 tourism 台灣好行路線、班表、票價與即時到站
有聲號誌 audible_signals 行人有聲號誌位置、啟動方式與主管機關

Client 與 AsyncClient 共用上述查詢入口。basic 可直接呼叫指定版本的端點並傳入端點支援的 OData 參數。提供 cache_ttl 的查詢預設關閉快取,傳入秒數即可啟用。

上游端點及授權方式請見 TDX 線上 API 說明。

OData 查詢

查詢結果可用條件篩選、排序與分頁。fields 涵蓋清單查詢的欄位,包含巢狀欄位與陣列,錯誤的欄位或型別可在執行前由型別檢查器發現。

from tdx import Query, fields
from tdx.bus import BusStop

stop = fields.bus_stop
query = (
    Query[BusStop]()
    .where(stop.name.zh_tw.contains("車站") | stop.name.en.startswith("Main"))
    .near(stop.position, longitude=121.517, latitude=25.047, radius=300)
    .order_by(stop.id.asc())
)
stops = client.bus.stops("Taipei", query=query, limit=20)

陣列欄位使用 any 與 all,條件以 &、|、~ 組合。query 也接受原始的 OData 參數。

XML

tdx.xml.parse_xml 以 pydantic-xml 模型解析 get_xml 取得的內容,不展開外部實體,也不存取網路。此功能需要 xml 選用相依套件。

回傳資料

清單查詢回傳不可變的 Records,info 提供更新時間與版本。各類資料共用 Name、Position、時間與日期型別。

Records 可用 to_polars()、to_pandas()、to_arrow() 匯出,巢狀欄位以點號命名,例如 name.zh_tw。Position 提供 distance_to()、to_shapely() 與 to_geohash()。匯出功能需要對應的選用相依套件。

連線

暫時性的連線錯誤、逾時與伺服器錯誤會自動重試,次數由 retries 設定。TDX 指定等待時間時會依其等待,權杖失效時會重新取得。所有錯誤皆繼承 tdx.exceptions.TDXError。

指定 cache_dir 可將回應保存在磁碟。之後的查詢會先向 TDX 確認資料是否更新,未更新時不重新下載,確認請求仍計入用量。快取不保存存取權杖。

貢獻

歡迎到 GitHub Issues 回報問題或提出 API 需求。

請見變更紀錄。資料由運輸資料流通服務平臺提供。tdx-tw 為非官方套件,與交通部無關。


TDX SDK 以 MIT 授權釋出。

Metadata

Release files for tdx-tw 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for tdx-tw 0.1.1
File Size Uploaded Provenance Actions
tdx_tw-0.1.1.tar.gz 123.7 kB Without provenance Details for tdx_tw-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for tdx-tw 0.1.1
File Interpreter ABI Platform Actions
tdx_tw-0.1.1-py3-none-any.whl Python 3 none any Details for tdx_tw-0.1.1-py3-none-any.whl

Total release size: 255.5 kB

Release files / tdx_tw-0.1.1.tar.gz

Download URL tdx_tw-0.1.1.tar.gz
Size 123.7 kB
Tags Source
SHA-256 checksum
How to use checksums
fa0e56734957149a04a1d73d56e6e71a0e5abefea990fe46f810780df102e1e8
BLAKE2b-256 checksum
How to use checksums
0860e286967c796a9fc49212de286ca51b75f554448d87c987d55eac1bb16459
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / tdx_tw-0.1.1-py3-none-any.whl

Download URL tdx_tw-0.1.1-py3-none-any.whl
Size 131.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0538ebd9946b865f5f7d7f431fccd837e954d781241268ba86c32aaf435621de
BLAKE2b-256 checksum
How to use checksums
16224bb37f53f9552dcae0c980e5cf7034e12ade825c27ed30c9850b8285eb62
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for tdx-tw 0.1.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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A 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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page