Skip to content
Dickson S. Guedes edited this page May 17, 2021 · 11 revisions

Examples of using Notion SDK for Python [WIP]

To play with this examples we expect that you've followed the instructions for notion-sdk-py's instalation and usage.

CRUD

To reproduce this CRUD example:

  • create a Database in Notion with title: Test Notion SDK for Python Database
  • on the "Tags" column create two labels: Animal, Vegetal
  • create a new column called Link of type URL
  • create a new column called Value of type Number

Then follow this steps to create pages on a database:

  • search for database by its name
  • create each page using a for loop
    • basic check for error or success
# CRUD Example 1
import sys
import random
import notion_client

# replace with your Token
NOTION_TOKEN = 'secret_XyZXyZXyZXyZXyZXyZXyZXyZXyZXyZ'

NOTION_DATABASE_NAME = "Test Notion SDK for Python Database"

notion = notion_client.Client(auth=NOTION_TOKEN)

print(f"Searching database '{NOTION_DATABASE_NAME}' ...", end="", flush=True)

search_database = notion.search(**{
    'query': NOTION_DATABASE_NAME,
    'property': 'object',
    'value': 'database'
}).json()

if len(search_database['results']) == 0:
    print(" not found!")
    sys.exit()

print(" found!")

my_database_id = search_database['results'][0]['id']

my_database = notion.databases.retrieve(database_id=my_database_id).json()

for page_id in range(1, 4):
    rand_page_type = random.choice(['Animal', 'Vegetal'])

    new_page_props = {
        'Name': {'title': [{'text': {'content': f"My Page of {rand_page_type} {page_id}"}}]},
        'Value': {'number': page_id},
        'Link': {'type': 'url', 'url': f"http://examples.org/page/{page_id}"},
        'Tags': {'type': 'multi_select', 'multi_select': [{'name': rand_page_type}]}
    }

    notion_page = notion.pages.create(
        parent={'database_id': my_database['id']},
        properties=new_page_props
    ).json()

    if notion_page['object'] == 'error':
        print("ERROR", notion_page['message'])
        continue

    print(f"Page for {rand_page_type} {page_id} created with id {notion_page['id']}")

You should got an output like this:

Searching database 'Test Notion SDK for Python Database' ... found!
Page for Vegetal 1 created with id ac0dc8ba-2ac8-42b1-9eb6-afbeabf36576
Page for Animal 2 created with id 506f3942-70e3-4c9c-a85b-0c3facd1b718
Page for Vegetal 3 created with id b5752ee4-b6a1-4839-b679-0569ef2e9ef0

If you get the output:

Searching database Test Notion SDK for Python Database... not found!

... check the Database name

If you get errors like this:

ERROR mNNm is an invalid select option "Animal".
ERROR mNNm is an invalid select option "Animal".
ERROR mNNm is an invalid select option "Vegetal".

back to start and check the "Tags" columns.

Clone this wiki locally