做企业内部系统时,经常会遇到一个需求:
把飞书里的组织架构、部门、员工同步到自己的系统。或者两边系统需要适配
一开始我以为这个需求很简单,后来真正做的时候发现:
- 飞书部门是树形结构
- 接口有分页
- 请求频率有限制
- 用户和部门需要关联
- 大公司部门层级很多
所以这篇文章不只是简单调接口,而是从实际开发角度,完整实现:
数据获取------>数据清洗------数据整理
最终效果:
技术部 -> 后端组 -> 张三
技术部 -> 前端组 -> 李四
财务部 -> 王五
最后生成一个完整的 Excel 通讯录。
一、为什么不能直接获取全部用户?
很多人第一次看接口会觉得: 直接调一个用户列表接口不就行了?
实际上不行。
因为飞书组织架构是:部门 -> 子部门 -> 子子部门
所以正确做法是:
先获取部门
↓
递归遍历所有子部门
↓
再获取每个部门下的直属用户
二、获取子部门列表(带分页)
之前有一篇文章已经写过,这里部分可以直接去看另外一篇文章,详细操作

三、获取部门直属用户
飞书接口:
飞书部门直属用户接口文档
同样有分页。
示例代码:
python
def get_users_by_department(access_token, department_id):
all_users = []
page_token = None
while True:
url = "https://open.feishu.cn/open-apis/contact/v3/users/find_by_department"
headers = {"Authorization": f"Bearer {access_token}"}
params = {
"department_id": department_id,
"department_id_type": "open_department_id",
"user_id_type": "open_id",
"page_size": 50,
}
if page_token:
params["page_token"] = page_token
try:
resp = session.get(url, headers=headers, params=params, timeout=30).json()
except requests.exceptions.SSLError as e:
print(f" ⚠ SSL错误,等待2秒后重试...")
import time
time.sleep(2)
resp = session.get(url, headers=headers, params=params, timeout=30).json()
if resp.get("code") != 0:
print(f" ⚠ 获取部门 {department_id} 用户失败: code={resp.get('code')}, msg={resp.get('msg')}")
break
items = resp.get("data", {}).get("items", [])
all_users.extend(items)
page_token = resp.get("data", {}).get("page_token")
has_more = resp.get("data", {}).get("has_more", False)
if not has_more or not page_token:
break
return all_users
四、组装部门+用户数据
python
def get_all_users_in_departments(access_token, departments):
all_user_rows = []
for dept in departments:
dept_id = dept["open_department_id"]
dept_name = dept["name"]
users = get_users_by_department(access_token, dept_id)
print(f" 部门 [{dept_name}] 获取到 {len(users)} 个用户")
for u in users:
user_row = {
"department_id": dept["department_id"],
"department_name": dept_name,
"open_department_id": dept_id,
"user_id": u.get("user_id", ""),
"open_id": u.get("open_id", ""),
"union_id": u.get("union_id", ""),
"name": u.get("name", ""),
"en_name": u.get("en_name", ""),
"nickname": u.get("nickname", ""),
"email": u.get("email", ""),
"mobile": u.get("mobile", ""),
"city": u.get("city", ""),
"country": u.get("country", ""),
}
all_user_rows.append(user_row)
return all_user_rows
五、导出 Excel
python
import pandas as pd
df = pd.DataFrame(final_data)
df.to_excel(
"feishu_users.xlsx",
index=False
)
print("Excel 导出成功")
Excel:
| 部门 | 姓名 | 手机号 | 邮箱 |
|---|---|---|---|
| 技术部 | 张三 | xxx | xxx |
| 后端组 | 李四 | xxx | xxx |
文中写的是示例数据,记录开发方式