5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

notion apiとpythonで本管理の備忘録

Last updated at Posted at 2021-06-08

訂正

記事内でgoogle books api使ったけど誤情報orデータがないが多すぎるから国会図書館とかのほうがいいかも

事前準備

  • pythonの環境設定
  • NotionのAPIキーの取得
  • 対象ページにintegrationsを招待
  • 対象ページのidをメモ

Notionのテーブル?設定

image.png

こんな感じでTitle, Author, PublishedDate, ISBNを定義する.
それぞれプロパティはtitle, text,text,numberにした.

流れ

ISBN(13桁) --> google books api --> Notion API

  • google books apiからはタイトル,著者名,出版日,ISBNを取得
  • Notion APIでPOSTする

使い方

python bookpost.py <13桁のISBN>

コード

  • プロパティの種類で書き方が違うことに注意.
  • textはrich_textって書く.
  • data=json.dumps(data)のとこを癖で日本語のエスケープ書くとpostでエラーになる.
bookpost.py
import json
import sys

import requests

NOTION_ACCESS_TOKEN = YOUR_SECRET_KEY
NOTION_PAGE_ID = YOUR_PAGE_ID


def request_googleapi(isbn):
    # print(isbn)
    url: str = "https://www.googleapis.com/books/v1/volumes"
    try:
        response = requests.get(url, params={"q": "isbn" + isbn})
        response.raise_for_status()
    except requests.exceptions.RequestException as e:
        print("error : ", e)
        print(response.text)
        exit(1)
    return response.json()


def POST_dict(data):
    dic = {}
    dic["title"] = data["items"][0]["volumeInfo"]["title"]
    dic["author"] = ", ".join(data["items"][0]["volumeInfo"]["authors"])
    dic["date"] = data["items"][0]["volumeInfo"]["publishedDate"]
    tmp = data["items"][0]["volumeInfo"]["industryIdentifiers"]
    value_list = [x["identifier"] for x in tmp if x["type"] == "ISBN_13"]
    value = value_list[0] if len(value_list) else 0
    dic["isbn"] = value
    return dic


def notion_post(bo):
    url: str = "https://api.notion.com/v1/pages"
    try:
        headers = {
            "Authorization": NOTION_ACCESS_TOKEN,
            "Content-Type": "application/json",
            "Notion-Version": "2021-05-13",
        }
        data = {
            "parent": {"database_id": NOTION_PAGE_ID},
            "properties": {
                "Title": {
                    "type": "title",
                    "title": [{"text": {"content": bo["title"]}}],
                },
                "Author": {
                    "type": "rich_text",
                    "rich_text": [{"text": {"content": bo["author"]}}],
                },
                "PublishedDate": {
                    "type": "rich_text",
                    "rich_text": [{"text": {"content": bo["date"]}}],
                },
                "ISBN": {"type": "number", "number": int(bo["isbn"])},
            },
        }
        response = requests.post(url=url, headers=headers, data=json.dumps(data))
        response.raise_for_status()
    except requests.exceptions.RequestException as e:
        print("error : ", e)
        print(response.text)
        exit(1)


isbn = sys.argv[1]
if len(isbn) != 13:
    exit(1)
a = request_googleapi(isbn)
bo = POST_dict(a)
notion_post(bo)
5
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?