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

第6章 ワークスペース検索とユーザー情報取得

Notion ワークスペース全体をキーワードで横断検索する Search API と、ワークスペース内のメンバー情報や Bot アカウントの情報を取得する Users API の活用法を解説します。

Search API によるワークスペース横断検索

インテグレーションが共有されているページやデータベースの中から、タイトルに含まれるキーワードで検索できます。 ID がわからないページを動的に探す際などに大変便利です。

キーワード検索の基本

import os
from dotenv import load_dotenv
from notion_client import Client

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

# "会議" というキーワードを含むページやデータベースを検索
search_results = notion.search(
    query="会議",
    page_size=5
)

for result in search_results.get("results", []):
    obj_type = result["object"]  # "page" または "database"
    item_id = result["id"]
    
    # ページとデータベースでタイトルの格納場所が異なる点に注意
    if obj_type == "page":
        props = result.get("properties", {})
        title_prop = props.get("title") or props.get("名前") or {}
        titles = title_prop.get("title", [])
        title_text = titles[0]["plain_text"] if titles else "(タイトルなし)"
    else:
        titles = result.get("title", [])
        title_text = titles[0]["plain_text"] if titles else "(タイトルなし)"
        
    print(f"[{obj_type.upper()}] {title_text} (ID: {item_id})")

検索対象の絞り込み(ページのみ / データベースのみ)

filter オプションを指定することで、検索結果をページのみ、またはデータベースのみに限定できます。

# データベースのみを検索対象にする
db_results = notion.search(
    query="プロジェクト",
    filter={
        "value": "database",
        "property": "object"
    }
)

ユーザー情報(Users API)の取得

Notion ワークスペース内のユーザー一覧や、特定のユーザー情報を取得できます。 担当者プロパティ(People)にユーザーを割り当てたい場合などに、ユーザーの id を特定するために利用します。

ワークスペースのユーザー一覧取得

users_response = notion.users.list()

for user in users_response.get("results", []):
    user_id = user["id"]
    name = user.get("name", "名称不明")
    user_type = user.get("type")  # "person" または "bot"
    
    email = ""
    if user_type == "person":
        email = user.get("person", {}).get("email", "")
        
    print(f"名前: {name} | 種別: {user_type} | メール: {email} | ID: {user_id}")

自分自身(Bot)の情報を取得する

インテグレーション自身の名前やワークスペース内での ID を確認するには、users.me() を使用します。

my_bot = notion.users.me()
print(f"Bot 名: {my_bot.get('name')}")
print(f"Bot ユーザーID: {my_bot.get('id')}")