NotionAPI(Python)を触ってみる【Notion,Python】

最近Notionというものを教えてもらいました!!(今更ですが) TrelloとEvernoteから乗り換えるのにいろいろと連携したりGASとの連携とかもあるので,scriptの移行のためにNotionAPIを触っていきたいと思います

<span style="color: #ff0000">NotionのAPIは2020/12現在 APIは非公式になっています</span>

今回は試しに触ってみるだけになるかと思われます.

以下NotionAPIとTrelloで毎日をタスクをアーカイブにしたものです

ayousanz.hatenadiary.jp

非公式サイトを確認する

github.com

このサイトで多くの方がすでに作られているのでこちらを使っていきます.

使い方等はこちらのReadMeに書かれています(今回はほぼReadMeを試すだけ??)

Notion Tokenを取得する

以下のサイトにやり方は書かれているので,参考にしてください

www.notion.so

環境を構築する

` Note: the latest version of notion-py requires Python 3.5 or greater. ‘と書いているので,ちょっと現在最新versinoのPython 3.9.1を使ってみたいと思います.

AnacondaでもPython3.9~に対応してるみたいなので,安心です

  1. conda crate -n notion python=3.9 で作成します.
  2. requirements.txtがあったので,こちらも入れていきます.
  3. pip install -r requirements.txt で依存ライブラリを入れていきます
  4. pip install notion なぜか Notionライブラリだけ入らないので,追加で入れます.

タイトルの取得とタイトルの更新

Quickstart
この部分をやってみます. 先ほど取得したTokenをいれて,テスト用のページの作成→URLを取得します

from notion.client import NotionClient

# Obtain the `token_v2` value by inspecting your browser cookies on a logged-in (non-guest) session on Notion.so
client = NotionClient(token_v2="your token")

# Replace this URL with the URL of the page you want to edit
page = client.get_block("page url")

print("The old title is:", page.title)

# Note: You can use Markdown! We convert on-the-fly to Notion's internal formatted text data structure.
page.title = "The title has now changed, and has *live-updated* in the browser!"

実行すると以下のようになります.

tableの操作(2021-3-2 追記)

tableの取得

url = "page url"
cv = client.get_collection_view(url)

for row in cv.collection.get_rows():
    print(row.title)

tableへの書き込み

row."なまえ"の部分は自分のtableのコラムの名前と一致しないと書き込みできないみたいです. また日本語はだめだったので英語のほうがいいと思います.

row = cv.collection.add_row()
row.name = "Just some data"
row.listName = "test"
row.deadline = datetime.date.today()
row.description = "hoge"