政府統計處為所有網上統計表提供機器可讀的 API 端點。本使用者指南說明如何向這些 API 端點發出請求、運用 Python 擷取統計數據,以及與人工智能(AI)協作,並詳述技術規格、整合步驟、請求範例和 AI 協作的實用例子。
基礎網址、回應格式及 OpenAPI 規範概述
用於擷取統計數據的 Python 程式碼範例
用於將你的 AI 代理連接到官方統計數字的 SKILL.md 檔案及用 AI 打造你的專屬檢視的提示詞範例
關於可用 API 一覽表及本使用者指南中資訊的使用須知
GET https://www.censtatd.gov.hk/api/get.php
| 名稱 | 類型 | 必要 | 說明 |
|---|---|---|---|
id |
字串 | 是 | 統計表編號(table_id),例如 110-01001 |
lang |
字串 | 是 | en | tc | sc — 文字描述語言 |
full_series |
字串 | 是 | 設定為 "1" 以取得完整數列 |
成功的回應是一個JSON對象。下方顯示一個回應範例。
{
"header": {
"status": {
"name": "Success",
"code": 0,
"description": "Query success",
"apiHelp": "..."
},
"title": "...",
"tablenote": [...],
"source": "Census and Statistics Department",
"count": {
"noOfRecords": 1234,
"started": "...",
"finished": "...",
"durationSeconds": 0.1234
}
},
"dataSet": [
{
"freq": "...",
"period": "...",
"sv": "...",
"svDesc": "...",
"figure": 1234,
"sd_value": "...",
...
}]
}
下面顯示的是政府統計處網上統計表 API 的 OpenAPI 3.0 規範。
openapi: 3.0.3
info:
title: APIs for C&SD Web Tables
description: These are the APIs for C&SD Web Tables
version: 1.0.0
servers:
- url: https://www.censtatd.gov.hk/api
tags:
- name: statisticalTables
description: Get full series statistics for Web Tables
paths:
/get.php:
get:
tags:
- statisticalTables
summary: Retrieve the statistics for Web Tables
description: Returns the requested C&SD Web Tables in JSON format.
operationId: getStatisticalTable
parameters:
- name: id
in: query
description: |
Web Table code (`table_id`), e.g. `110-01001`.
Only one table may be requested per call.
required: true
schema:
type: string
- name: lang
in: query
description: |
Language of the textual descriptions.
Only `en` | `tc` | `sc` are allowed (case-insensitive; prefer lowercase).
required: true
schema:
type: string
enum:
- en
- tc
- sc
- name: full_series
in: query
required: true
description: |
Set to `"1"` for the full series.
This parameter is served as validation as well.
schema:
type: string
enum:
- "1"
responses:
"200":
description: successful request
content:
application/json:
schema:
$ref: "#/components/schemas/TableResponse"
"404":
description: Resource not found
"4XX":
description: Client error
"5XX":
description: Server error
components:
schemas:
TableResponse:
type: object
required:
- header
properties:
header:
$ref: "#/components/schemas/Header"
dataSet:
type: array
description: |
Array of observation records.
Present only on a successful request, with the description of the query being "Query Success".
It may be omitted or empty on failure.
items:
$ref: "#/components/schemas/DataRecord"
Header:
type: object
required:
- status
- count
properties:
status:
$ref: "#/components/schemas/Status"
title:
type: string
description: Web Table Title
tablenote:
type: array
description: Footnotes and explanatory notes (language-dependent)
items:
type: string
source:
type: string
description: Data source and contact information
count:
$ref: "#/components/schemas/Count"
Status:
type: object
required:
- name
- code
- description
properties:
name:
type: string
enum:
- Success
- Fail
code:
type: integer
description: |
0 = Query success
1 = Validation error
enum:
- 0
- 1
description:
type: string
message:
oneOf:
- type: string
nullable: true
- type: array
items:
type: string
nullable: true
description: |
Error detail(s) when `code = 1`.
Null, omitted, or empty on success.
apiHelp:
type: string
format: uri
description: Link to the API helper page on the corresponding Web Table webpage.
Count:
type: object
properties:
noOfRecords:
type: integer
minimum: 0
description: Number of records returned in `dataSet`
started:
type: string
format: date-time
description: Server-side processing start timestamp (ISO 8601 with offset)
finished:
type: string
format: date-time
description: Server-side processing end timestamp (ISO 8601 with offset)
durationSeconds:
type: number
format: float
description: Processing duration in seconds
DataRecord:
type: object
description: The statistics for the selected Web Table.
additionalProperties: true
以下程式碼片段可將網上統計表的完整數列擷取,並載入至pandas DataFrame。你可以點擊「試一試」以選擇所需的網上統計表,系統將自動生成一段可直接複製並使用的執行程式碼。
import requests
import pandas as pd
import getpass
def fetch_table(table_id, lang,proxies) -> pd.DataFrame:
"""Fetch a C&SD Web Table (full series) and return a flat DataFrame."""
url = "https://www.censtatd.gov.hk/api/get.php"
params = {
"id": table_id,
"lang": lang,
"full_series": "1",
}
resp = requests.get(url, params=params, timeout=60,
headers = {
'Content-Type':'application/json',
'User-Agent': 'Python Request'
},
proxies = proxies)
resp.raise_for_status()
records = resp.json().get("dataSet")
df = pd.json_normalize(records)
return df
proxies = None
# 取消註解以下程式碼以設定代理
# username = input('Username: ')
# password = getpass.getpass('Password: ')
# proxyname = 'proxy.example.com:port' # Change to your Proxy Name
# proxies = {
# 'http': 'http://' + username + ':' + password + '@' + proxyname,
# 'https': 'http://' + username + ':' + password + '@' + proxyname,
# }
# 例子:表110-01001:按性別及年齡組別劃分的人口
df = fetch_table("110-01001", lang="tc", proxies=proxies)
以下技能(Skill)可以透過從API網頁中檢索 API 端點來幫助回答統計問題。你可以複製 Skill 並另存為 SKILL.md,或直接點擊「下載」儲存檔案,隨後即可匯入至 AI 代理。
---
name: retrieve-official-statistics-from-api-webpage
description: 從政府統計處(統計處)的官方即時 API 一覽表頁面(英文:https://www.censtatd.gov.hk/en/API.html,繁體中文:/tc/,簡體中文:/sc/)擷取並回答統計處統計資料的查詢。當使用者提供一個或多個自然語言統計問題,或要求查詢統計處統計表、通脹、本地生產總值、人口、勞工、貿易、物價、零售業或其他香港官方統計數據的問題時使用。
---
# 從 API 網頁擷取官方統計數據
## 概述
作為一名專注於香港官方統計數據的專業數據科學家,針對每個自然語言查詢(或查詢清單),僅使用即時統計處 API 清單網頁及相應的 API 端點。切勿自行編造統計表 ID、數字、單位或解釋。
## 語言選擇
- 英語查詢或混合語言 → lang=en 及網頁 https://www.censtatd.gov.hk/en/API.html
- 繁體中文 → lang=tc 及 /tc/API.html
- 簡化中文 → lang=sc 及 /sc/API.html
根據用戶訊息的語言進行偵測。若不明確,預設為英語。
## 工作流程(嚴格順序)
1. **在即時網頁上尋找最相符的統計表**。
擷取相應語言的 API 清單網頁。**切勿預先分類查詢或假設相關性。** 將用戶文字的語意意圖與目前列出的統計表標題/描述/報表編號進行配對。優先選擇最精確的匹配項,而非寬泛的匹配項。
2. **選取端點**。
選取最相符的端點。完全依照文件記載建構完整 URL:
`https://www.censtatd.gov.hk/api/get.php?id={table_id}&lang={lang}&full_series=1`
3. **檢索並驗證 JSON**。
向端點發出請求。檢查 `header.status`:
- `code=0` / `name=Success` → 繼續。
- 否則,透明地回報失敗情況(驗證錯誤、404 等),並停止該查詢。
擷取:
- `header.title`、`header.tablenote`(註腳/注意事項)、`header.source`
- `dataSet` 數組
4. **時間區間處理**
- 明確指定年份/期數/範圍 → 將 `dataSet` 篩選為相符的 `period` 值。
- 未指定區間 → 回傳最新可用的 `figure`,並清楚說明參考期。
- 務必保留 `sd_value` 或註解中存在的特殊顯示、註腳、標記、「N.A.」或其他指示符。
5. **建構答案**
- **僅**根據擷取的 JSON + 即時清單網頁 + `https://www.censtatd.gov.hk/` 下的任何概念及方法網頁作答。
- **切勿**查閱或引用任何其他網站。
- 包含統計說明(`svDesc`)、參考期、定義、特殊顯示(`sd_value`) ,以及來自 `tablenote` 的每個相關註腳。
- 對於與趨勢相關的問題,提供相關數據的清晰表格;僅當圖表能夠提升清晰度且坐標軸不具誤導性時才添加圖表。
- 維持正式、精確的語氣。
6. **多重查詢**
獨立處理每個查詢,保留原始順序,並以清楚的標題分隔答案。
7. **失敗情況**
如果即時清單網頁上沒有出現合適的統計表,針對該查詢明確說明,切勿自行編造數據或連結。如果 API 請求失敗,回報確切狀態。
## 輸出期望
- 簡短說明選取的統計表 ID 及配對原因。
- 呈現關鍵數據時需附帶適當單位、參考期,以及任何必要的腳註。
- 如果繪製圖表,其座標軸應不具誤導性。
- 維持正式、精確的語氣。
- 清楚地組織多查詢回應(每個查詢為一節)。
- 如果數據檢索失敗或端點回傳錯誤,透明地回報失敗情況。
複製以下任何提示詞到配備畫板工具(Canvas Tool)或建構工具(Build Tool)的程式碼代理或聊天機器人中,並將
table_id 替換為所需網上統計表的編號(如:110-01001)。你亦可以點擊「試一試」以選擇所需的網上統計表,系統將自動生成一段可供直接複製並使用的提示詞。
你是一名數據分析師,正在為香港官方統計數據構建互動統計圖解。
任務:
1. 從 API 端點獲取數據:
https://www.censtatd.gov.hk/api/get.php?id={table_id}&lang=tc&full_series=1
2. 將 JSON 載入 pandas DataFrame,保留時期、描述和數值。
3. 製作:
- 分析 JSON 結構。
- 識別關鍵數值指標和維度,並構建帶有動態篩選器和圖表的HTML5互動統計圖解。
- 顯示所有可用數據。
4. 在每個視覺效果和隨附文字中引用統計處及統計表編號。
5. 切勿捏造任何數值。如果 API 失敗,報告 HTTP 狀態並停止。
你是一名數據分析師,正在為香港官方統計資料建立具有篩選功能的HTML表格。
當用戶詢問有關官方統計數據的問題時:
1. 使用以下命令獲取完整系列:
GET https://www.censtatd.gov.hk/api/get.php?id={table_id}&lang=tc&full_series=1
2. 建立一個帶有摘要卡片、搜尋/篩選、排序和分頁功能的 HTML 表格。
3. 顯示所有可用數據。
4. 切勿捏造任何數值。如果請求失敗,報告 HTTP 狀態並停止。
並排顯示兩個網上統計表的數據。 要使用的統計表: - 表1:{table_id_1}(例如 110-02001 按區議會分區劃分的陸地面積、陸上人口及人口密度) - 表2:{table_id_2}(例如 210-06821 按區議會分區、性別及年齡劃分的勞動人口數目及勞動人口參與率) 步驟: 1. 使用以下命令獲取兩個完整數列: - 表 1:GET https://www.censtatd.gov.hk/api/get.php?id={table_id_1}&lang=tc&full_series=1 - 表 2:GET https://www.censtatd.gov.hk/api/get.php?id={table_id_2}&lang=tc&full_series=1 2. 盡可能將所選取的兩個統計表的數據對齊到共同的時間軸上。如果無法對齊,則停止製作。 3. 製作卡片及互動統計圖解,以顯示兩個統計表的數據。 4. 切勿捏造任何數值。如果請求失敗,報告 HTTP 狀態並停止。