<jupyter_start><jupyter_text>Notion - Get page **Tags:** notion productivity  Input  Import library<jupyter_code>from notion import Notion
import naas<jupyter_output><empty_output><jupyter_text>Variables<jupyter_code># Enter Notion Token API
token = "<KEY>"

# Enter database url
url = "https://www.notion.so/Axel-2ccdafe28955478b8c9d70bda0044c86"
notion = Notion().connect(token)<jupyter_output><empty_output><jupyter_text>Model  Get properties<jupyter_code>page = notion.page()<jupyter_output><empty_output><jupyter_text>Get content👉  The content of a page is return as a array of blocks by the Notion API ```json{  "object": "block",  "id": "9bc30ad4-9373-46a5-84ab-0a7845ee52e6",  "created_time": "2021-03-16T16:31:00.000Z",  "last_edited_time": "2021-03-16T16:32:00.000Z",  "has_children": false,  "type": "to_do",  "to_do": {    "text": [      {        "type": "text",        "text": {          "content": "Lacinato kale",          "link": null        },        "annotations": {          "bold": false,          "italic": false,          "strikethrough": false,          "underline": false,          "code": false,          "color": "default"        },        "plain_text": "Lacinato kale",        "href": null      }    ],    "checked": false  }}```Each block is a dictionary with different keys:- id *(str)*- has_children *(bool)*- created_time *(str)*- last_edited_time *(str)*- type *(str)*- {type} *(dict)*{type} is an object with type-specific block informationList of block type:- paragraph- heading(1,2,3)- bullet list item- numbered list item- to_do_blocks- toggle block- child page blockMore info here: https://developers.notion.com/reference/block 🚨 BEAWARE OF:- I can't retreive the children element of a block: it's not the same behaviour than the one in Block Object look like it's a bug from the API - Some data information are lost. Exemple: the color of the text and the link - blank blocks are count as a paragraph we maybe need to create a new category for them or delete them from the result<jupyter_code>def fetch_raw_blocks(token_api, page_url):
    page_id = get_id_from_url(page_url)
    url = f'https://api.notion.com/v1/blocks/{page_id}/children'
    headers = create_headers(token_api, _VERSION)
    response = requests.get(url, headers=headers)
    res = requests.get(url, headers=headers)
    try:
        res.raise_for_status()
    except requests.HTTPError as e:
        return e
    return res.json()['results']

blocks = fetch_raw_blocks(TOKEN_API, PAGE_URL)
pprint(blocks[0])<jupyter_output><empty_output><jupyter_text>Functions<jupyter_code>_VERSION = '2021-08-16'

headers = {'Authorization': f'Bearer {TOKEN_API}',
           'Notion-Version': f'{_VERSION}'}

def get_id_from_url(url):
    return url.split('-')[-1]

def get(url):
    res = requests.get(url, headers=headers)
    try:
        res.raise_for_status()
    except requests.HTTPError as e:
        return e
    return res.json()

def get_content(page_url):
    # Get id from page
    page_id = get_id_from_url(page_url)
    url = f'https://api.notion.com/v1/blocks/{page_id}/children'
    
    # Get json
    res_json = get(url)
    blocks = res_json.get("results")

    # Parse json
    contents = []
    for block in blocks:
        content = {
            "object": block.get("object"),
            "id": block.get("id"),
            "type": block.get("type"),
            "has_children": block.get("has_children"),
            "created_time": datetime.strptime(block.get("created_time"), '%Y-%m-%dT%H:%M:%S.000Z'),
            "last_edited_time": datetime.strptime(block.get("last_edited_time"), '%Y-%m-%dT%H:%M:%S.000Z'),
        }
        type_contents = block.get(block.get("type")).get("text")
        if type_contents is not None:
            for t in type_contents:
                annotations = t.get("annotations")
                content.update(annotations)
                text = t.get("text")
                content.update(text)
        contents.append(content)
    
    df = pd.DataFrame(contents)
    return df<jupyter_output><empty_output><jupyter_text>Output  Get properties : Table format<jupyter_code>df_properties = get_properties(PAGE_URL)
df_properties
PAGE_URL = "https://www.notion.so/naas-official/Weekly-Sync-20-05-2021-f59c898f5ad34587a544f9e06b45be5f"

# Get id from page
page_id = get_id_from_url(PAGE_URL)
url = f'https://api.notion.com/v1/pages/{page_id}'

# Get json
res_json = get(url)

# Parse json
content = {
    "object": res_json.get("object"),
    "id": res_json.get("id"),
    "url": res_json.get("url"),
    "archived": res_json.get("archived"),
    "created_time": datetime.strptime(res_json.get("created_time"), '%Y-%m-%dT%H:%M:%S.000Z'),
    "last_edited_time": datetime.strptime(res_json.get("last_edited_time"), '%Y-%m-%dT%H:%M:%S.000Z'),
}
properties = res_json.get("properties")
pprint(properties)
for p in properties:
    print(p)<jupyter_output><empty_output><jupyter_text>Get content : Table format<jupyter_code>df_content = get_content(PAGE_URL)
df_content<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1426872770511296, 'fraction_numerical': 0.025762980578676178, 'mean_word_length': 3.643054277828887, 'pattern_counts': {'":': 34, '<': 30, '<?xml version=': 0, '>': 30, 'https://': 6, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '647266', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 1801, 'n_tokens_neox': 1718, 'n_words': 370, 'path': 'Notion/Notion_Get_page.ipynb', 'repo_name': 'jorgeariasm/Plantillas-ML', 'size': '5091'}