如何在Notion页面中检索数据库ID



我在Notion页面中有一个数据库表。我想使用Notion API将值填充到数据库中。但是,由于我有多个这样的页面,所以每次都硬编码数据库ID是不切实际的。有没有办法通过Notion API在Notion页面中检索数据库ID?或者有没有一种方法可以找出";对象";在页面中,以便我可以循环浏览它们并找到它们的属性?谢谢

数据库本身是block,更确切地说是child_database。您可以通过检索页面的子块并过滤type = child_database来获取它的id。几周前,我在Python中实现了这一点。

实用方法

def _child_blocks(block_id, header, js):
"""
Retrieves child blocks of a block from the notion api blocks endpoint
:param block_id: id of the block to retrieve child blocks from (e.g. a page)
:param header: authentication header for Notion api
:param js: body of the query, generated by the jsons library
:return: json of the response
"""
read_url = f"https://api.notion.com/v1/blocks/{block_id}/children"
res = requests.request("GET", read_url, headers=header, params=js)
data = res.json()
return data
def _empty_filter(next_cursor=None):
"""
Json to query the appointments database for all entries, useful for pagination
:param next_cursor: cursor to start from
:return: json to use as body of a query
"""
data = {
"page_size": 30
}
if next_cursor:
data["start_cursor"] = next_cursor
return data

最终方法

def _child_database(page_id, header) -> str:
"""
Returns the database id of the first child database block
:param page_id: id of the page to get the child database from
:param header: authentication header for Notion api
:return: database id of the first child database block, empty str if no child database block found
"""
data = _child_blocks(page_id, header, _empty_filter())
while True:
for result in _results(data):
if result['type'] == 'child_database':
item_database_id = result['id']
return item_database_id
if not data['has_more']:
break
data = _child_blocks(page_id, header, _empty_filter(data['next_cursor']))
return ""

最新更新