在 Python 中调用飞书 API,你可以参考以下步骤¹:
1. **安装 requests 模块**:这是一个常用的 Python HTTP 库,可以发送 HTTP 请求。
2. **获取授权凭证**:在使用 API 之前,我们需要先获取授权凭证。这包括 `app_access_token`(访问 App 资源相关接口),`tenant_access_token`(访问企业资源相关接口)和 `user_access_token`(访问用户资源相关接口)。在这里,我们主要介绍如何获取 `tenant_access_token`¹:
- 在管理后台创建企业自建应用;
- 记录应用凭证内的 AppID 和 AppSecret 备用;
- 从左侧三种应用功能任选一种;
- 根据后续操作需要选择所需权限;
- 发布应用(应用于所有部门);
- 利用 Request 获取 `app_access_token`(企业自建应用)。
3. **发送 POST 请求**:具体请求地址、Header、Body 会在接口声明中提及,执行 `request.post()` 后会接收返回 Body¹。例如:
```python
# 请求地址
url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/"
# 请求 Header(字典形式储存)
header = {"content-type":"application/json", "Authorization":"Bearer " + str(tat)}
# 请求 Body(字典形式储存)
post_data = {"app_id":"xxx", "app_secret":"xxx"}
# 发送 POST 请求
r = requests.post(url, data=post_data, headers=header)
```
4. **发送 GET 请求**:与 POST 请求方式大致相同,具体参数内容参见接口声明¹。例如:
```python
# 请求 Header(字典形式储存)
header = {"content-type":"application/json", "Authorization":"Bearer " + str(tat)}
# 请求地址
url = "https://open.feishu.cn/open-apis/contact/v1/tenant/custom_attr/get"
# 发送 GET 请求
r = requests.get(url, headers=header)
```
5. **解析 JSON**:为便于对返回 Body 进行处理,我们通常将返回信息以 JSON 形式展示,方法如下:`r.json()`¹。
此外,你还可以使用 `feishu-python-sdk`²,这是一个用于和飞书开放平台交互的 Python 库,它支持同步调用和异步调用,并实现了订阅事件和卡片交互回调。
希望这些信息对你有所帮助!如果你有其他问题,欢迎随时向我提问。
源: 与必应的对话, 2023/10/30
(1) Python调用飞书API接口 - 知乎 - 知乎专栏. https://zhuanlan.zhihu.com/p/127962748.
(2) feishu-python-sdk · PyPI. https://pypi.org/project/feishu-python-sdk/.
(3) 通过Python调用飞书API的流程——以读取电子表格为例 - 知乎. https://zhuanlan.zhihu.com/p/481205393.
(4) Python调用飞书Api上传本表格 - CSDN博客. https://blog.csdn.net/weixin_44888962/article/details/121237622.
(5) undefined. https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/.
(6) undefined. https://open.feishu.cn/open-apis/contact/v1/tenant/custom_attr/get.
(7) undefined. https://open.feishu.cn/open-apis/contact/v1/scope/get.
(8) undefined. https://open.feishu.cn/open-apis/contact/v1/department/info/get?department_id=.
(9) undefined. https://open.feishu.cn/open-apis/contact/v1/user/add.
(10) undefined. https://s3-fs.pstatp.com/static-resource/v1/0a04c4b7-4edd-4cb3-a277-a1f6c609af4g.
(11) undefined. https://open.feishu.cn/document/ukTMukTMukTM/uUTNz4SN1MjL1UzM.
(12) undefined. https://open.feishu.cn/document/ukTMukTMukTM/uYjNwUjL2YDM14iN2ATN.
(13) undefined. https://open.feishu.cn/document%29.
(14) undefined. https://open.feishu.cn/open-apis/authen/v1/index?redirect_uri=https://www.baidu.com&app_id=cli_a1039072c9f8900cclass.