C&SD offers machine-readable API endpoints for all Web Tables. This user guide explains how to send requests to these API endpoints, retrieve statistical data using Python, and collaborate with artificial intelligence (AI). It provides details of technical specifications, integration steps, sample requests, and practical examples of AI collaboration.
An overview of the base URL, response format and OpenAPI Specification
Sample Python script for retrieving statistical data
A SKILL.md file for connecting your AI agent to official statistics and sample prompts for
building your own view
Points to note for the use of the List of Available APIs and information in this user guide
GET https://www.censtatd.gov.hk/api/get.php
| Name | Type | Required | Description |
|---|---|---|---|
id |
string | Yes | Table code (table_id), e.g. 110-01001 |
lang |
string | Yes | en | tc | sc — language of textual descriptions |
full_series |
string | Yes | Set to "1" for the full series |
A successful response is a JSON object. An example on the response is shown below.
{
"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": "...",
...
}]
}
The OpenAPI 3.0 specification for the C&SD Web Tables API is shown below.
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
The snippet below fetches a full data series of a Web Table into a pandas DataFrame. You may click “Try it” to select the Web Table you need; the system will automatically generate a ready-to-run script that you can copy and use directly.
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
# Uncomment the following code to set the proxies
# 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,
# }
# Example: Table 110-01001 : Population by sex and age group
df = fetch_table("110-01001", lang="en", proxies=proxies)
The Skill below can help answer statistical questions by retrieving API endpoints from the API webpage. You
may copy the Skill and save it as SKILL.md, or click “Download”
to save the file directly, and then import it into
your AI agent.
---
name: retrieve-official-statistics-from-api-webpage
description: Fetch and answer Hong Kong C&SD statistical queries from the official live API list pages (https://www.censtatd.gov.hk/en/API.html for English, /tc/ for Traditional Chinese, /sc/ for Simplified Chinese). Use when the user asks natural-language questions about C&SD tables or series, inflation, GDP, population, labour, trade, prices, retail sales, or other official Hong Kong statistics.
---
# Retrieve Official Statistics from API Webpage
## Overview
Act as a professional data scientist specialising in Hong Kong official statistics. For every natural-language query (or list of queries), work exclusively from the **live** C&SD API list page and the corresponding API endpoints. Never invent table IDs, figures, units, or interpretations.
## Language Selection
- English query or mixed → `lang=en` and page `https://www.censtatd.gov.hk/en/API.html`
- Traditional Chinese → `lang=tc` and `/tc/API.html`
- Simplified Chinese → `lang=sc` and `/sc/API.html`
Detect from the user’s message language. Default to English if ambiguous.
## Workflow (strict order)
1. **Locate best-fit table(s) on the live webpage**.
Fetch the appropriate language API list page. **Do not pre-categorise the query or assume relevance.** Match the semantic intent of the user’s words to the table title/description/table number currently listed. Prefer the most specific match over a broader one.
2. **Select endpoint(s)**.
Select the best-fit endpoint(s). Construct the full URL exactly as documented:
`https://www.censtatd.gov.hk/api/get.php?id={table_id}&lang={lang}&full_series=1`
3. **Retrieve and validate JSON**.
Call the endpoint. Inspect `header.status`:
- `code=0` / `name=Success` → proceed.
- Otherwise, report the failure (validation error, 404, etc.) transparently and stop for that query.
Extract:
- `header.title`, `header.tablenote` (footnotes/caveats), `header.source`
- `dataSet` array
4. **Time-period handling**
- Explicit year/period/range requested → filter `dataSet` to matching `period` values.
- No period specified → return the latest available `figure` and clearly state the reference period.
- Always preserve the special display, footnote, notation, “N.A.”, or other indicators present in the `sd_value` or notes.
5. **Answer construction**
- Answer **solely** from the fetched JSON + the live list page + any concept/method pages under `https://www.censtatd.gov.hk/`.
- Do **not** consult or cite any other website.
- Include statistical presentation (`svDesc`), reference period, definitions, special display (`sd_value`) and every relevant footnote from `tablenote`.
- For questions related to trends, present a clean table of the relevant series; add a chart only when it improves clarity and axes are not misleading.
- Maintain the formal, precise tone.
6. **Multiple queries**
Process each independently, preserve original order, and separate answers with clear headings.
7. **Failure cases**
If no suitable table appears on the live list page, state this explicitly for that query and do not invent data or links. If the API call fails, report the exact status.
## Output Expectations
- Briefly state the selected table ID and the reason for the match.
- Present key figures with proper units, reference periods, and any necessary footnotes.
- If a chart is drawn, its coordinate axes **should not** be misleading.
- Maintain the formal, precise tone.
- Structure multi-query responses clearly (one section per query).
- If data retrieval fails or the endpoint returns an error, report the failure transparently.
Copy any of the following prompts into a coding agent or chatbot with the Canvas Tool or
the Build Tool. Replace the table_id with the serial number(s) of the Web
Table(s) you need
(e.g. 110-01001). You may also click
“Try it” to select the Web Table(s) you need; the system
will then automatically generate a prompt that you can copy and use directly.
You are a data analyst building an interactive dashboard for Hong Kong official statistics.
Task:
1. Fetch the data from the API endpoint:
GET https://www.censtatd.gov.hk/api/get.php?id={table_id}&lang=en&full_series=1
2. Load the JSON into a pandas DataFrame, keeping period, description and figure.
3. Produce:
- Analyse the JSON structure.
- Identify key numeric metrics and dimensions, and build an HTML5 interactive dashboard with dynamic filters and charts.
- Show all available data.
4. Cite C&SD and the table code in every visual and in the accompanying text.
5. Do not fabricate any figures. If the API fails, report the HTTP status and stop.
You are a data analyst building an HTML table with filter functions for Hong Kong official statistics.
Task:
1. Fetch the full series with:
GET https://www.censtatd.gov.hk/api/get.php?id={table_id}&lang=en&full_series=1
2. Build an HTML table with summary cards, search/filter, sorting, and pagination.
3. Show all available data.
4. Do not fabricate any figures. If the request fails, report the HTTP status and stop.
Display data of two Web Tables side-by-side. Tables to use: - Table 1:{table_id_1}(e.g. 110-02001 Land area, land population and population density by District Council district) - Table 2:{table_id_2}(e.g. 210-06821 Labour force and labour force participation rate by District Council district, sex and age) Steps: 1. Fetch both full series with: - Table 1: GET https://www.censtatd.gov.hk/api/get.php?id={table_id_1}&lang=en&full_series=1 - Table 2: GET https://www.censtatd.gov.hk/api/get.php?id={table_id_2}&lang=en&full_series=1 2. Align the data of two selected tables on a common time axis whenever possible. If their time axes cannot be aligned, stop the production. 3. Produce cards and interactive dashboards to display data from the two tables. 4. Do not fabricate any figures. If the request fails, report the HTTP status and stop.