Skip to main content

Recursively Fetch All Departments

The department API only returns the direct child departments of the specified node. To obtain the complete organization tree, start from the root department, paginate through each node, and continue traversing.

Calling Sequence​

  1. Call Query Department Details and use $root to obtain the root department.
  2. Call List Sub-departments.
  3. Read all direct child departments of the current node by offset and limit.
  4. Add the child departments to the pending queue until the queue is empty.

Python Example​

from collections import deque
import requests

API_BASE = "https://alimail-cn.aliyuncs.com"


def list_all_departments(access_token: str) -> list[dict]:
headers = {"Authorization": f"Bearer {access_token}"}
root = requests.get(
f"{API_BASE}/v2/departments/$root",
headers=headers,
timeout=15,
)
root.raise_for_status()

result = [root.json()]
pending = deque([root.json()["id"]])
while pending:
parent_id = pending.popleft()
offset = 0
while True:
response = requests.get(
f"{API_BASE}/v2/departments/{parent_id}/departments",
headers=headers,
params={"offset": offset, "limit": 100},
timeout=15,
)
response.raise_for_status()
payload = response.json()
children = payload.get("departments", [])
result.extend(children)
pending.extend(item["id"] for item in children)
offset += len(children)
if offset >= payload.get("total", 0) or not children:
break
return result

For large organizations, add retry logic, rate limiting, and checkpoint logging. Use department IDs for deduplication to avoid infinite loops caused by abnormal data.

Reference: Original Example.