Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Free REST API for Chinese Administrative Regions and Hierarchical Data Retrieval

Tech 3

The service exposes a GET endpoint for querying administrative boundaries, region codes, and hierarchical location data within mainland China. The underlying dataset is periodically synchronized to reflect official civil affairs updates.

Endpoint: https://www.xujian.tech/atlapi/data/m/city/tree HTTP Method: GET

Query Parameters

Parameter Type Requirement Description
code string Required Static authentication token. Obtain via the designated WeChat mini-program sign-in process. Keep secure and do not modify.
adCode string Conditional Standard administrative division identifier. Provide either this or name to execute the lookup.
name string Conditional Fuzzy match string for region names. Provide either this or adCode to execute the lookup.
full string Optional Set to 1 to automatically resolve and include immediate child administrative levels in the returned tree.

Response Schema

The API returns a standardized JSON enevlope containing status indicators and the requested dataset.

Field Type Description
code integer Status indicator. 200 denotes success; other values indicate errors.
msg string Human-readable status description (e.g., "succeed.").
data object Root node containing region metadata and nested subdivisions.
→ name string Official region name (province, municipality, district, or county).
→ adCode string Administrative code.
→ cityCode string or null Telephone area code.
→ parentCode string or null Administrative code of the immediate superior region.
→ children array Nested array of subordinate regions, recursively applying the same schema.

Implementation Example

The following Python script demonstrates how to construct the request, handle dynamic parameters, and parse the hierarchical output.

import requests
import json
import sys

def query_location_tree(api_token, region_code=None, search_term=None, expand_children=False):
    service_url = "https://www.xujian.tech/atlapi/data/m/city/tree"
    
    query_params = {
        "code": api_token,
        "adCode": region_code if region_code else "",
        "name": search_term if search_term else ""
    }
    
    if expand_children:
        query_params["full"] = "1"

    try:
        resp = requests.get(service_url, params=query_params, timeout=10)
        payload = resp.json()
        
        if payload.get("code") == 200:
            return payload["data"]
        else:
            print(f"API Error: {payload.get('msg')}", file=sys.stderr)
            return None
    except requests.exceptions.RequestException as err:
        print(f"Network failure: {err}", file=sys.stderr)
        return None

if __name__ == "__main__":
    # Configuration
    AUTH_KEY = "replace_with_your_static_token"
    TARGET_AD_CODE = "370100"
    
    # Execute query
    hierarchy = query_location_tree(
        api_token=AUTH_KEY,
        region_code=TARGET_AD_CODE,
        expand_children=True
    )
    
    if hierarchy:
        print(json.dumps(hierarchy, indent=4, ensure_ascii=False))

Sample Output

Upon successful execution, the data object contains a nested tree structure. The example below illustrates the recursive relationship from the national root down to municipal districts.

{
  "code": 200,
  "msg": "succeed.",
  "data": {
    "adCode": "100000",
    "name": "中华人民共和国",
    "cityCode": null,
    "parentCode": null,
    "children": [
      {
        "adCode": "370000",
        "name": "山东省",
        "cityCode": null,
        "parentCode": "100000",
        "children": [
          {
            "adCode": "370100",
            "name": "济南市",
            "cityCode": "0531",
            "parentCode": "370000",
            "children": [
              {
                "adCode": "370102",
                "name": "历下区",
                "cityCode": "0531",
                "parentCode": "370100",
                "children": []
              },
              {
                "adCode": "370104",
                "name": "槐荫区",
                "cityCode": "0531",
                "parentCode": "370100",
                "children": []
              }
            ]
          }
        ]
      }
    ]
  }
}

Access Policy & Monitoring

The endpoint operates without usage caps, rate limiting, or subscription fees. Developers can track daily invocation metrics and service health through the dedicated monitoring dashboard at https://www.xujian.tech/monitor. Authentication tokens must be securely managed to prevent unauthorized consumption.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.