|
| 1 | +from os import environ |
| 2 | + |
| 3 | +import requests |
| 4 | +from pydotenvs import load_env |
| 5 | + |
| 6 | + |
| 7 | +load_env() |
| 8 | +TEST_NOTION_TOKEN = environ["TEST_NOTION_TOKEN"] |
| 9 | +TEST_NOTION_PAGE = environ["TEST_NOTION_PAGE"] |
| 10 | + |
| 11 | + |
| 12 | +headers = { |
| 13 | + "Accept": "application/json", |
| 14 | + "Notion-Version": "2022-06-28", |
| 15 | + "Content-Type": "application/json", |
| 16 | + "Authorization": TEST_NOTION_TOKEN, |
| 17 | +} |
| 18 | + |
| 19 | +# Create database |
| 20 | +todo_db_data = { |
| 21 | + "parent": {"type": "page_id", "page_id": TEST_NOTION_PAGE}, |
| 22 | + "icon": { |
| 23 | + "type": "external", |
| 24 | + "external": {"url": "https://super.so/icon/dark/check-square.svg"}, |
| 25 | + }, |
| 26 | + "title": [ |
| 27 | + { |
| 28 | + "type": "text", |
| 29 | + "text": { |
| 30 | + "content": "ToDo List", |
| 31 | + }, |
| 32 | + } |
| 33 | + ], |
| 34 | + "properties": { |
| 35 | + "Name": {"title": {}}, |
| 36 | + "Done": {"checkbox": {}}, |
| 37 | + }, |
| 38 | +} |
| 39 | +todo_database_id = requests.post( |
| 40 | + "https://api.notion.com/v1/databases", headers=headers, json=todo_db_data |
| 41 | +).json()["id"] |
| 42 | + |
| 43 | + |
| 44 | +# Add pages to database |
| 45 | +for page_title, is_done in zip(("Item 1", "Item 2", "Item 3"), (False, True, False)): |
| 46 | + todo_page_data = { |
| 47 | + "parent": {"database_id": todo_database_id}, |
| 48 | + "properties": { |
| 49 | + "Name": {"title": [{"text": {"content": page_title}}]}, |
| 50 | + "Done": {"checkbox": is_done}, |
| 51 | + }, |
| 52 | + } |
| 53 | + requests.post( |
| 54 | + "https://api.notion.com/v1/pages", headers=headers, json=todo_page_data |
| 55 | + ) |
| 56 | + |
| 57 | +# Query database for certain property |
| 58 | +filter_data = {"property": "Done", "checkbox": {"equals": False}} |
| 59 | +open_tasks = requests.post( |
| 60 | + f"https://api.notion.com/v1/databases/{todo_database_id}/query", |
| 61 | + headers=headers, |
| 62 | + json={"filter": filter_data}, |
| 63 | +).json()["results"] |
| 64 | +for task in open_tasks: |
| 65 | + page_id = task["id"] |
| 66 | + title_property_id = task["properties"]["Name"]["id"] |
| 67 | + title = requests.get( |
| 68 | + f"https://api.notion.com/v1/pages/{page_id}/properties/{title_property_id}", |
| 69 | + headers=headers, |
| 70 | + ).json()["results"][0] |
| 71 | + print(title["title"]["text"]["content"]) |
| 72 | + |
| 73 | +# Delete database |
| 74 | +requests.patch( |
| 75 | + f"https://api.notion.com/v1/databases/{todo_database_id}", |
| 76 | + headers=headers, |
| 77 | + json={"archived": True}, |
| 78 | +) |
0 commit comments