-
-
Notifications
You must be signed in to change notification settings - Fork 141
Examples
Guillaume Gelin edited this page May 18, 2021
·
11 revisions
To play with this examples we expect that you've followed the instructions for notion-sdk-py
's installation and usage.
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 typeURL
; - create a new column called
Value
of typeNumber
; - delete the blank lines from database;
Then follow this steps to create pages on a database:
- authenticate with secret token
- search for database by its name
- create some pages using a
for
loop- basic check for
error
orsuccess
- basic check for
# 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']
# this is a bit useless since we already have the database id
my_database = notion.databases.retrieve(database_id=my_database_id).json()
# this will create 3 pages
for page_id in range(1, 4):
rand_page_type = random.choice(['Animal', 'Vegetal'])
# set how other properties types here:
# https://developers.notion.com/reference/database#database-property
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.