Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

第7章 実践自動化レシピ

Notion API と Python を組み合わせた、実用的で日常の作業を効率化する 3 つの実践自動化レシピを紹介します。

レシピ 1:毎日の「日報ページ」を自動起票する

毎日朝に実行し、その日の日付をタイトルにした日報ページを自動生成するスクリプトです。 親ページ配下に「本日の予定」「振り返り」「メモ」のブロックをあらかじめ用意します。

import os
from datetime import datetime
from dotenv import load_dotenv
from notion_client import Client

load_dotenv()
notion = Client(auth=os.getenv("NOTION_TOKEN"))
parent_page_id = os.getenv("NOTION_DAILY_PAGE_ID")

today_str = datetime.now().strftime("%Y-%m-%d")
page_title = f"{today_str} 日報"

# 本文の初期テンプレート
children_blocks = [
    {
        "object": "block",
        "type": "heading_2",
        "heading_2": {
            "rich_text": [{"type": "text", "text": {"content": "本日のタスク・予定"}}]
        }
    },
    {
        "object": "block",
        "type": "to_do",
        "to_do": {
            "rich_text": [{"type": "text", "text": {"content": "朝会に参加する"}}],
            "checked": False
        }
    },
    {
        "object": "block",
        "type": "heading_2",
        "heading_2": {
            "rich_text": [{"type": "text", "text": {"content": "ふりかえり・メモ"}}]
        }
    },
    {
        "object": "block",
        "type": "paragraph",
        "paragraph": {
            "rich_text": [{"type": "text", "text": {"content": ""}}]
        }
    }
]

new_daily_page = notion.pages.create(
    parent={"page_id": parent_page_id},
    properties={
        "title": [{"text": {"content": page_title}}]
    },
    children=children_blocks
)

print(f"日報ページを作成しました: {page_title} (ID: {new_daily_page['id']})")

レシピ 2:Web サイトの情報を収集してデータベースに自動保存する

Web サイトのニュースや技術記事のタイトルと URL を取得し、Notion の「あとで読む」データベースに自動登録するスクリプトです。

import os
from dotenv import load_dotenv
from notion_client import Client

load_dotenv()
notion = Client(auth=os.getenv("NOTION_TOKEN"))
database_id = os.getenv("NOTION_DATABASE_ID")

# 収集した記事のサンプルデータ(スクレイピング結果など)
articles = [
    {"title": "Notion API 活用入門", "url": "https://example.com/notion-guide", "category": "Tech"},
    {"title": "Python による業務自動化の基本", "url": "https://example.com/python-auto", "category": "Python"}
]

for article in articles:
    notion.pages.create(
        parent={"database_id": database_id},
        properties={
            "記事タイトル": {
                "title": [{"text": {"content": article["title"]}}]
            },
            "URL": {
                "url": article["url"]
            },
            "カテゴリ": {
                "select": {"name": article["category"]}
            },
            "既読": {
                "checkbox": False
            }
        }
    )
    print(f"保存完了: {article['title']}")

レシピ 3:requests ライブラリによる生の REST API 操作

外部ライブラリ notion-client を使わず、標準的な HTTP 通信ライブラリ requests のみを用いて Notion API を呼び出すパターンです。 SDK が利用できない環境や、より軽量なプログラムを作成したい場合に有効です。

import os
import requests
from dotenv import load_dotenv

load_dotenv()
token = os.getenv("NOTION_TOKEN")
database_id = os.getenv("NOTION_DATABASE_ID")

url = f"https://api.notion.com/v1/databases/{database_id}/query"
headers = {
    "Authorization": f"Bearer {token}",
    "Notion-Version": "2022-06-28",
    "Content-Type": "application/json"
}

# POST リクエストでデータベースを検索
response = requests.post(url, headers=headers, json={"page_size": 5})

if response.status_code == 200:
    data = response.json()
    for row in data.get("results", []):
        row_id = row["id"]
        print(f"レコード ID: {row_id}")
else:
    print(f"エラー発生: {response.status_code} - {response.text}")