如何通过Python调用Notion API获取页面区块及子区块?
问题描述
我拥有一个Notion页面,链接为https://www.notion.so/Wiki-Page-For-a-Business-Case-8ec70cd1894711a862acc61a47fdb74d。我希望通过Python访问该页面并提取其区块,已成功创建连接并获取API Key,但无法通过URL或其他方式通过Notion API访问该页面。尝试使用Search API时返回验证错误:
{"object":"error","status":400,"code":"validation_error","message":"body failed validation: body.filter.content should be not present, instead was
\"Wiki Page for a Business Case\"."}
我的错误代码如下:
import requests url = "https://api.notion.com/v1/search" token = 'secret_S5PPXrnCcJ3mA1234gYSGHzvt123dYQE2j4112bePAMD' search_params = {"filter": {"value": "page", "property": "object", "content": "Wiki Page for a Business Case"}} headers = { "Authorization": "Bearer " + token, "accept": "application/json", "Notion-Version": "2022-06-28", "content-type": "application/json" } response = requests.post(url, json=search_params, headers=headers) print(response.text)
解决方法
1. 修正Search API的调用错误
你在Search API的请求参数里错误添加了filter.content字段,Notion Search API的filter结构中并没有这个参数。如果要按标题搜索页面,需把标题关键词放在query参数中,而非filter内。修正后的代码如下:
import requests url = "https://api.notion.com/v1/search" token = 'secret_S5PPXrnCcJ3mA1234gYSGHzvt123dYQE2j4112bePAMD' # 正确的搜索参数:用query指定标题关键词,filter仅过滤对象类型为page search_params = { "query": "Wiki Page for a Business Case", "filter": {"value": "page", "property": "object"} } headers = { "Authorization": "Bearer " + token, "accept": "application/json", "Notion-Version": "2022-06-28", "content-type": "application/json" } response = requests.post(url, json=search_params, headers=headers) print(response.json())
2. 更高效的直接访问:通过页面ID调用Retrieve Block Children API
既然你已经有页面URL,直接提取页面ID调用Retrieve Block Children API会更高效,无需搜索:
- 从页面URL中提取页面ID:
8ec70cd1894711a862acc61a47fdb74d(URL末尾的32位字符串) - 使用该ID直接获取页面下所有区块:
import requests page_id = "8ec70cd1894711a862acc61a47fdb74d" url = f"https://api.notion.com/v1/blocks/{page_id}/children" token = 'secret_S5PPXrnCcJ3mA1234gYSGHzvt123dYQE2j4112bePAMD' headers = { "Authorization": "Bearer " + token, "accept": "application/json", "Notion-Version": "2022-06-28" } # 处理分页:若区块较多,has_more为true时继续请求下一页 response = requests.get(url, headers=headers) blocks = response.json()["results"] while response.json().get("has_more"): next_cursor = response.json()["next_cursor"] response = requests.get(f"{url}?start_cursor={next_cursor}", headers=headers) blocks.extend(response.json()["results"]) # 打印所有区块内容 for block in blocks: print(block)
3. 检查必要的权限配置
确保完成以下操作,否则API会无法访问页面:
- 在Notion中将你的集成(创建API Key的那个集成)添加到目标页面:打开页面右上角
...→Add connections→ 选择你的集成名称 - 确认API Key对应的集成拥有
Read权限(创建集成时默认已开启)
内容的提问来源于stack exchange,提问作者STORM
相关产品推荐
相关产品推荐

