API User Guide

This user guide explains how to make requests to the available API endpoints for the C&SD statistical products, and retrieve statistical data using Python.

Back to the List of APIs

Overview

C&SD offers machine-readable API endpoints for official statistical products in English, Traditional Chinese, and Simplified Chinese. This user guide details technical specifications, integration steps, and sample requests.

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

Get Statistics by Python

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

import requests
import pandas as pd
import getpass
def fetch_product(product_id, lang,proxies) -> pd.DataFrame:
    """Fetch a C&SD statistical product (full series) and return a flat DataFrame."""
    url = "https://www.censtatd.gov.hk/api/get.php"
    params = {
        "id": product_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_product("110-01001", lang="en", proxies=proxies)
STEP 1 OF 2 STEP 2 OF 2 Choose a statistical product for the Python script. The Python script is ready. Statistical Product Choose a statistical product to continue. Press "Start" to get the script. No matching product found 0 statistical products shown {n} statistical product shown {n} statistical products shown Other Copied No statistical product selected
STEP 1 OF 2

Choose a statistical product for the Python script.

1 Select
2 Copy
Statistical Product
Choose a statistical product to continue.

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

Python — Fetch C&SD statistical products

                

OpenAPI Specification

Parameter for Requests

Name Type Required Description
idstringYesStatistical product code (product_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 available for C&SD statistical products
  description: These are the APIs available for C&SD statistical products
  version: 1.0.0
servers:
  - url: https://www.censtatd.gov.hk/api
tags:
  - name: statisticalProducts
    description: Get full series statistics for statistical products
paths:
  /get.php:
    get:
      tags:
        - statisticalProducts
      summary: Retrieve the statistics for statistical products
      description: Returns the requested C&SD statistical products in JSON format.
      operationId: getStatisticalProduct
      parameters:
        - name: id
          in: query
          description: |
            Statistical product code (`product_id`), e.g. `110-01001`.
            Only one product 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/ProductResponse"
        "404":
          description: Resource not found
        "4XX":
          description: Client error
        "5XX":
          description: Server error
components:
  schemas:
    ProductResponse:
      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: Statistical Product 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 statistical product 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 statistical product.
      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.