Notion In 5 Minutes - Code Snippets

Hey Coder! Here are simple code snippets you can use to get started with the Notion API. Check out the videos for quick, in depth explanations.

🎥 Watch the 5 Minute Authentication Video (1)

🎥 Watch the 5 Minute Write Video (2)

🎥 Watch the 5 Minute Read Video (3)

🎥 Watch the 5 Minute Database Read Video (4)

🎥 Watch the 5 Minute Database Write Video (5)

⭐️ Install the Notion API Client Library

📄 Notion API Documentation

💬 Questions & Answers

Install (Bash)

📋 Copy
pip install notion-client

Authentication (Python)

📋 Copy
          from notion_client import Client
from pprint import pprint

notion_token = ''
notion_page_id = ''

def main():
    client = Client(auth=notion_token)

    page_response = client.pages.retrieve(notion_page_id)

    pprint(page_response, indent=2)

if __name__ == '__main__':
    main()
          
        

Write (Python)

📋 Copy
          from notion_client import Client
from pprint import pprint

notion_token = ''
notion_page_id = ''

def write_text(client, page_id, text, type):
    client.blocks.children.append(
        block_id=page_id,
        children=[
            {
                "object": "block",
                "type": type,
                type: {
                    "rich_text": [
                        {
                            "type": "text",
                            "text": {
                                "content": text
                            }
                        }
                    ]
                }
            }
        ]
    )

def main():
    client = Client(auth=notion_token)

    write_text(client, notion_page_id, 'Hello World!', 'to_do')

if __name__ == '__main__':
    main()
  
        

Read (Python)

📋 Copy
          from notion_client import Client
from pprint import pprint
import json

notion_token = ''
notion_page_id = ''

def write_text(client, page_id, text, type='paragraph'):
    client.blocks.children.append(
        block_id=page_id,
        children=[{
            "object": "block",
            "type": type,
            type: {
                "rich_text": [{ "type": "text", "text": { "content": text } }]
            }
        }]
    )

def write_dict_to_file_as_json(content, file_name):
    content_as_json_str = json.dumps(content)

    with open(file_name, 'w') as f:
        f.write(content_as_json_str)

def read_text(client, page_id):
    response = client.blocks.children.list(block_id=page_id)
    return response['results']

def create_simple_blocks_from_content(client, content):

    page_simple_blocks = []

    for block in content:

        block_id = block['id']
        block_type = block['type']
        has_children = block['has_children']
        rich_text = block[block_type].get('rich_text')

        if not rich_text:
            return


        simple_block = {
            'id': block_id,
            'type': block_type,
            'text': rich_text[0]['plain_text']
        }

        if has_children:
            nested_children = read_text(client, block_id)
            simple_block['children'] = create_simple_blocks_from_content(client, nested_children)

        page_simple_blocks.append(simple_block)


    return page_simple_blocks
    

def main():
    client = Client(auth=notion_token)

    content = read_text(client, notion_page_id)

    write_dict_to_file_as_json(content, 'content.json')

    simple_blocks = create_simple_blocks_from_content(client, content)

    write_dict_to_file_as_json(simple_blocks, 'simple_blocks.json')

if __name__ == '__main__':
    main()

        

Database Read (Python)

📋 Copy
          import uuid
from notion_client import Client
from pprint import pprint
import json

notion_token = ''
notion_page_id = ''
notion_database_id = ''

def write_dict_to_file_as_json(content, file_name):
    content_as_json_str = json.dumps(content)

    with open(file_name, 'w') as f:
        f.write(content_as_json_str)

def read_text(client, page_id):
    response = client.blocks.children.list(block_id=page_id)
    return response['results']

def safe_get(data, dot_chained_keys):
    '''
        {'a': {'b': [{'c': 1}]}}
        safe_get(data, 'a.b.0.c') -> 1
    '''
    keys = dot_chained_keys.split('.')
    for key in keys:
        try:
            if isinstance(data, list):
                data = data[int(key)]
            else:
                data = data[key]
        except (KeyError, TypeError, IndexError):
            return None
    return data

def main():
    client = Client(auth=notion_token)
    
    db_info = client.databases.retrieve(database_id=notion_database_id)

    write_dict_to_file_as_json(db_info, 'db_info.json')

    db_rows = client.databases.query(database_id=notion_database_id)

    write_dict_to_file_as_json(db_rows, 'db_rows.json')

    simple_rows = []

    for row in db_rows['results']:
        user_id = safe_get(row, 'properties.UserId.title.0.plain_text')
        date = safe_get(row, 'properties.Date.date.start')
        event = safe_get(row, 'properties.Event.select.name')

        simple_rows.append({
            'user_id': user_id,
            'date': date,
            'event': event
        })

    write_dict_to_file_as_json(simple_rows, 'simple_rows.json')


if __name__ == '__main__':
    main()


        

Database Write (Python)

📋 Copy
          import uuid
from notion_client import Client
from pprint import pprint
import json

notion_token = ''
notion_page_id = ''
notion_database_id = ''

def write_text(client, page_id, text, type='paragraph'):
    client.blocks.children.append(
      block_id=page_id,
      children=[{
        "object": "block",
        "type": type,
        type: {
          "rich_text": [{ "type": "text", "text": { "content": text } }]
        }
      }]
    )

def write_dict_to_file_as_json(content, file_name):
    content_as_json_str = json.dumps(content)

    with open(file_name, 'w') as f:
        f.write(content_as_json_str)

def read_text(client, page_id):
    response = client.blocks.children.list(block_id=page_id)
    return response['results']

def safe_get(data, dot_chained_keys):
    '''
        {'a': {'b': [{'c': 1}]}}
        safe_get(data, 'a.b.0.c') -> 1
    '''
    keys = dot_chained_keys.split('.')
    for key in keys:
        try:
            if isinstance(data, list):
                data = data[int(key)]
            else:
                data = data[key]
        except (KeyError, TypeError, IndexError):
            return None
    return data

def create_simple_blocks_from_content(client, content):

    page_simple_blocks = []

    for block in content:

        block_id = block['id']
        block_type = block['type']
        has_children = block['has_children']
        rich_text = block[block_type].get('rich_text')

        if not rich_text:
            return


        simple_block = {
            'id': block_id,
            'type': block_type,
            'text': rich_text[0]['plain_text']
        }

        if has_children:
            nested_children = read_text(client, block_id)
            simple_block['children'] = create_simple_blocks_from_content(client, nested_children)

        page_simple_blocks.append(simple_block)


    return page_simple_blocks
    

def write_row(client, database_id, user_id, event, date):

    client.pages.create(
        **{
            "parent": {
                "database_id": database_id
            },
            'properties': {
                'UserId': {'title': [{'text': {'content': user_id}}]},
                'Event': {'select': {'name': event}},
                'Date': {'date': {'start': date}}
            }
        }
    )


def main():
    client = Client(auth=notion_token)

    user_id = str(uuid.uuid4())
    event = 'Visitor'
    date = '2022-12-25'
    
    write_row(client, notion_database_id, user_id, event, date)

if __name__ == '__main__':
    main()

        

Notion API Questions

Where are the docs for methods like client.pages.* and client.retrieve.*?

Convert Your Notion Pages Into Podcasts