Reputation: 83
I have got a database table within a Notion page. I would like to use the Notion API to populate values to the database. However, since I have multiple of these pages it would be impractical to hardcode the database ID each time. Is there a way to retrieve the database ID within a Notion page via the Notion API? Or is there a way to find out what "objects" are within the page so that I can loop through them and find their attributes? Thanks.
Upvotes: 1
Views: 1327
Reputation: 146
The database itself is a block
, more precisely a child_database
. You can obtain it's id by retrieving the child blocks of the page and filtering for type = child_database
. I implemented this in Python a few weeks ago.
Utility methods
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
Final method
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 ""
Upvotes: 1