API User Guide

C&SD offers machine-readable API endpoints for all Web Tables in English, Traditional Chinese, and Simplified Chinese. This user guide explains how to send requests to the API endpoints provided by C&SD for its Web Tables, 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.

Back to the List of APIs

Base URL

GET https://www.censtatd.gov.hk/api/get.php

Get Statistics by Python

The snippet below fetches a full data series of a Web Table into a panda DataFrame. You may click “Try it” to select a table and copy a ready-to-run script.

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)
STEP 1 OF 2 STEP 2 OF 2 Choose a Web Table for the Python script. The Python script is ready. Table Choose a table to continue. Press "Start" to get the script. No matching table found 0 tables shown {n} table shown {n} tables shown Other Copied No Web Table selected
STEP 1 OF 2

Choose a Web Table for the Python script.

1 Select
2 Copy
Table
Choose a table to continue.

You can click the button in the top-right corner to copy the Python script.

Python — Fetch C&SD Web Table

                

Connect to Your AI Agent

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.

SKILL.MD

---
name: retrieve-official-statistics-from-api-webpage
description: Fetch and answer Hong Kong C&SD statistical queries from the live official 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.

Build Your Own View with AI

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 one you need. You may click “Try it” to select Web Table(s) and copy a ready-to-use prompt.

Prompt 1 — Build a HTML5 Interactive Dashboard

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.

Prompt 2 — Build a Data Table with Filter Function

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.

Prompt 3 — Display Data of Two Web Tables Side-By-Side

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.
STEP 1 OF 2 STEP 2 OF 2 Choose a prompt first, and then table(s). The prompt is ready. Please choose a sample prompt first. Please select a table to fill into the prompt. Please select two different tables for the selected prompt. Table Tables Choose a prompt to continue. Choose a table to continue. Choose two different tables to continue. Select Table 1 to continue. Select Table 2 to continue. Press "Start" to get the prompt. No matching table found 0 tables shown {n} table shown {n} tables shown Other Already selected as the other table Copied No Web Table selected
STEP 1 OF 2

Choose a prompt first, and then table(s).

1 Select
2 Copy

Please choose a sample prompt first.

Prompt 1
Sample Prompts
Table
Table 1
Table 2
No Web Table selected
Choose a prompt to continue.

You can click the button in the top-right corner to copy the prompt.

Prompt 1 — Build a HTML5 Interactive Dashboard

                    

OpenAPI Specification

Parameter for Requests

Name Type Required Description
idstringYesTable code (table_id), e.g. 110-01001
langstringYesen | tc | sc — language of textual descriptions
full_seriesstringYesSet to "1" for the full series

Example Call

GET https://www.censtatd.gov.hk/api/get.php?id=110-01001&lang=en&full_series=1

OpenAPI 3.0 (YAML)

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

Response Format

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": "...",
            ...
        }]
}

Important Notices

  • All figures shall be based on those published on the C&SD Website.
  • If collaborating with artificial intelligence (AI), please carefully verify the accuracy of the data, as AI-generated results may deviate from the facts.
  • Please carefully refer to the concepts and methods of the relevant statistics before interpreting or analysing the figures.
  • The information contained in this website is for reference only. Whilst the Government endeavours to ensure the accuracy of the information on this website, no statement, representation, guarantee or warranty of any kind (whether express or implied) is given by the Government as to the accuracy of the information. The Government shall not be liable for any errors in, omissions from, or misstatements or misrepresentations (express or implied), concerning any information, and shall not have or accept any liability, obligation or responsibility (including liability for negligence) whatsoever for any loss, destruction or damage (including without limitation consequential loss, destruction or damage) howsoever arising from or in respect of any supply of, use or misuse of or reliance on the information delivered on this website or inability to use it.
  • The Government is not responsible for any loss or damage whatsoever arising out of or in connection with any information on this website. The Government reserves the right to omit, suspend or edit all information on this website at any time in its absolute discretion without giving any reason or prior notice. Users are responsible for making their own assessment of all information contained on this website and are advised to verify such information by making reference, for example, to original publications and obtaining independent advice before acting upon it.