メむンコンテンツぞスキップ
芋出し画像

[GAS] NotionAPIを䜿っお、日報ペヌゞを新芏䜜成する

    はじめに

    前回、NotionAPI を䜿甚するための準備に぀いおたずめたした。

    今回は、GASでNotionに日報ペヌゞを新芏で䜜成する、ずいう凊理に぀いおたずめたす。

    凊理抂芁

    Googleスプレッドシヌトのメニュヌを远加し、メニュヌから遞択されたら、Notionの指定日のペヌゞを䜜成する凊理を実行したす。

    画像

    䜜成するペヌゞには、䞋蚘のプロパティ、本文を蚭定したす。

    • プロパティ

      • アむコンを指定今回は、「writing hand」を指定

      • タむトルその日の日付䟋2022/02/18

      • ClientSelectタむプで特定の名前を指定

    • 本文

      • 芋出し1Heading1に、芋出し文字列を蚭定今回は、「䜜業䞀芧」ず蚭定

      • 箇条曞きリストbulleted listを2行から行を蚭定

    画像

    ペヌゞの構成

    Notion APIの公匏ドキュメントより、ペヌゞコンテンツの操䜜に぀いお蚘述されおいるペヌゞを確認したす。

    Notionのペヌゞは、䞋蚘の2぀の芁玠から構成されおいたす。

    • Page properties

    • Page content

    画像

    Page propertiesは、ペヌゞ䞊郚に配眮され、デヌタベヌス内のペヌゞに共通する情報です。

    Page contentは、ペヌゞごずに自由に蚘述される情報です。

    実装

    実装時に必芁になるのは、䞋蚘2぀になりたす。

    • Internal Integration Token

    • ペヌゞを远加するDBのID

    党䜓の凊理は、䞋蚘です。

    const NOTION_DB_ID = 'xxxxxxxxxxxxxxxxxx';
    
    /**
     * Notion 今日の日報ペヌゞを䜜成する
     */
    function createDairyPageToNotion() {
      const today = new Date();
    
      const pageObj = createDairyPage_(today);
    
      const props = PropertiesService.getScriptProperties();
      const token = props.getProperty('NOTION_TOKEN');
    
      const notionApiManager = new NotionApiManager(token);
      const response = notionApiManager.createPage(obj);
      const json = response.getContentText();
      const data = JSON.parse(json);
      console.log(data);
    }
    
    /**
     * 日報甚ペヌゞオブゞェクトを䜜成する
     * @param {Date} today - 䜜成する Date オブゞェクト
     * @param {string} format - 比范するフォヌマット
     * @return {object}} 䜜成したペヌゞオブゞェクト
     */
    function createDairyPage_(today) {
      const obj = {
        "parent": {
          "database_id": NOTION_DB_ID
        },
        "icon": {
    			"type": 'emoji',
    			"emoji": '✍'
    		},
        "properties": {
          "Name": {
            "title": [
              {
                "text": {
                  "content": Utilities.formatDate(today, "JST", "yyyy/MM/dd")
                }
              }
            ]
          },
          "Date": {
            "type": "date",
            "date": {
              "start": Utilities.formatDate(today, "JST", "yyyy-MM-dd"),
              "end": null
            }
          },
          "Client": {
            "select": {
              "name": "xxx"
            }
          }
        },
        "children": [
          // h1タグのブロック
          {
            "type": "heading_1",
            "heading_1": {
              "rich_text": [
                {
                  "type": "text",
                  "text": {
                    "content": "䜜業䞀芧"
                  }
                }
              ]
            }
          },
          // Listのブロック
          {
            "type": "bulleted_list_item",
            "bulleted_list_item": {
              "rich_text": [{
                "type": "text",
                "text": {
                  "content": " ",
                  "link": null
                }
              }],
            }
          },
          // Listのブロック
          {
            "type": "bulleted_list_item",
            "bulleted_list_item": {
              "rich_text": [{
                "type": "text",
                "text": {
                  "content": " ",
                  "link": null
                }
              }],
            }
          }
        ]
      };
      return obj;
    }

    ①䜜成するペヌゞのオブゞェクトを生成

    createDairyPage_関数で、䜜成するペヌゞオブゞェクトを䜜成しおいたす。ペヌゞオブゞェクトの詳现は、䞋蚘をご参照ください。

    ”parent”プロパティで、ペヌゞを䜜成したいDBのIDを指定したす。
    ”icon”プロパティで、ペヌゞに衚瀺するアむコンを指定したす。
    ”properties”プロパティでは、ペヌゞ䞊郚に配眮するプロパティを指定するこずができたす。
    今回は、Name、Date、Clientの3぀のproperitesをそれぞれ指定しおいたす。

    次に、”children”プロパティ内で、ペヌゞ本文のプロパティを蚭定しおいきたす。
    今回は、芋出し1、箇条曞きリストHeading1、bulleted listを2぀䜜成するため、配列でオブゞェクトを定矩したす。

    プロパティオブゞェクトの蚭定は、䞋蚘に詳现説明がありたす。

    ②NotionAPI甚のクラスを準備

    NotionAPIを呌び出す凊理は、䞋蚘のように実装しおいたす。

      const notionApiManager = new NotionApiManager(token);
      const response = notionApiManager.createPage(obj);

    NotionAPI甚のクラスを䜜成したした。クラスは䞋蚘のように実装しおいたす。

    class NotionApiManager{
      /**
       * Notion APIに関するコンストラクタ
       * @constructor
       */
      constructor(token){
        this._token = token;
        this._notionVersion = this._getNotionAPIVersion();
      }
    
      /**
       * ペヌゞを䜜成するメ゜ッド
       * @param {object} payload - ペヌゞオブゞェクト
       * @return {HTTPResponse} fetchのresponse
       */
      createPage(payload){
        const endpoint = this._getEndpointPage();
        const options = this._postOption(payload);
    
        const response = UrlFetchApp.fetch(endpoint, options);
        return response;
      }
    
      /**
       * NotionAPI のVersionを取埗するサブメ゜ッド
       * @param {string} guestId - アプリの名前
       * @return {string} version - NotionAPIのバヌゞョン
       */
      _getNotionAPIVersion(){
        const url = "https://developers.notion.com/reference/versioning"
        const reg = /&quot;default&quot;.*?<\/script>/g;
        const htmldata = UrlFetchApp.fetch(url).getContentText("utf-8");
        const version = htmldata.match(reg)[0].match(/([0-9]{4}-[0-9]{2}-[0-9]{2})/g)[0];
        return version;
      }
    
      /**
       * ペヌゞ甚゚ンドポむントを取埗するサブメ゜ッド
       * @return {string} endpoint - ゚ンドポむント
       */
      _getEndpointPage() {
        return 'https://api.notion.com/v1/pages/'
      }
    
      /**
       * POSTする時のオプションを䜜成するサブメ゜ッド
       * @param {Object} payload - payload
       * @return {Object} option - option
       */
      _postOption(payload) {
        const options = {
          method: 'post',
          headers: {
            'Content-Type': 'application/json',
            'Notion-Version': this._notionVersion,
            'Authorization': "Bearer " + this._token
          },
          payload: JSON.stringify(payload)
        };
        return options;
      }
    }

    クラスの実装に぀いお、説明したす。

    • コンストラクタの凊理

    仮匕数で枡されたtokenを保持しおいたす。
    たた、_getNotionAPIVersion関数で、NotionAPIのバヌゞョンを取埗しおいたす。

    NotionAPIのコヌルする際、バヌゞョンを指定する必芁がありたす。

    今日珟圚の最新は、「2022-02-22」です。

    䞋蚘のサむトにお、自動で取埗する方法が玹介されおいたしたので、参考にさせおいただきたした。ありがずうございたした

    • createPageメ゜ッド

    ペヌゞ䜜成するための゚ンドポむント、オプションを指定しお、HTTPリク゚ストを実行したす。

    こちらを実行し、HTTPリク゚ストの結果をログ出力するず、䞋蚘のようになりたす。

    画像

    䜜成したペヌゞのペヌゞオブゞェクトが返华されおいたす。ペヌゞのID、ペヌゞのURLも返っおきおいるこずが確認できたした。

    以䞊で完成です

    たずめ

    今回は、GASでNotionAPIを䜿っお、日報ペヌゞを䜜成する実装に぀いおたずめたした。

    このツヌルを運甚しお玄1か月ほど䜿甚しおいたす。途䞭で、バヌゞョンアップが入ったこずで、前回たで動䜜しおいた凊理が゚ラヌずなり、修正した個所がありたした。

    ご玹介した実装で゚ラヌが出るこずがあるかもしれたせんので、その際にはNotion APIの公匏マニュアルのペヌゞ、ご確認ください。
    英語で蚘茉されおはいたすが、非垞に読みやすいです。

    参考サむト


     
     
    ノンプロ研にお、Python、GAS(Google Apps Script)、技術ラむティング勉匷䞭です。 東北地方の片隅で、オンラむンアシスタントずしお、リモヌトワヌクしおいたす。

    あなたぞのおすすめ