# 快速上手 (https://nolantw.github.io/tdx/)

tdx-tw 是運輸資料流通服務平臺（TDX）的 Python SDK，負責認證、呼叫 API 與驗證回應，並把資料整理成 Python 物件。

## 安裝

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

```shell
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 金鑰

至 [TDX](https://tdx.transportdata.tw/) 註冊會員，在會員中心取得 API 金鑰的 Client ID 與 Client Secret，並設為環境變數，SDK 會自動讀取：

```shell
# macOS、Linux
export TDX_CLIENT_ID="Client ID"
export TDX_CLIENT_SECRET="Client Secret"
```

```powershell
# Windows PowerShell
$env:TDX_CLIENT_ID = "Client ID"
$env:TDX_CLIENT_SECRET = "Client Secret"
```

## 第一個查詢

列出公車路線各站的到站時間：

```python
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`。

## 下一步

| 想做的事 | 閱讀 |
| --- | --- |
| 查詢公車到站時間、班表與票價 | [公車](/guides/bus) |
| 查詢火車、高鐵與捷運 | [軌道](/guides/rail) |
| 查詢自行車站與停車場空位 | [自行車](/guides/bike)、[停車](/guides/parking) |
| 找出座標附近的站牌與車站 | [附近查詢](/guides/nearby) |
| 規劃跨運具的路線 | [路線規劃](/guides/routing) |
| 查詢路況與道路事件 | [路況與道路事件](/guides/traffic) |
| 查詢航班與船班 | [航空](/guides/air)、[航運](/guides/ship) |
| 篩選、排序與分頁 | [篩選與分頁](/advanced/queries) |
| 非同步查詢、快取與重試 | [用戶端與快取](/advanced/clients) |
| 匯出表格 | [結果與匯出](/advanced/results) |
| 了解時間、名稱與缺值的規則 | [資料說明](/reading) |