LoginSignup
5
6

More than 3 years have passed since last update.

GoogleカレンダーAPIを用いてカレンダー一覧を取得する

Posted at

はじめに

いよいよ平成最後の日になりました。GoogleカレンダーのAPIを使う機会があったので、Google Calendar APIに関する記事を投稿します。

前提

  • Googleの開発者アカウントが作成済みであること
  • Calendar APIを有効化して、APIキーの取得ができていること

やりたいこと

  • Googleカレンダーで所有しているカレンダーの一覧を取得する(共有カレンダー含む)

一つ一つのカレンダーにIDが割り振られているため、動的にカレンダーの一覧を取得して、その中から特定のカレンダーを指定して操作することが可能になります。

実装

本記事では、カレンダーの一覧を取得してログに出力するための実装を記載します。

getAllCalendarList.js
'use strict';
const url = require('url');
const https = require('https');

const HTTP_RESPONSE_OK = 200;
const ACCESS_TOKEN = 'API実行に必要なアクセストークン';

// カレンダー一覧取得のためのAPI
let options = url.parse("https://www.googleapis.com/calendar/v3/users/me/calendarList");
options.method = "GET";
options.headers = {
    "Authorization":"Bearer " + ACCESS_TOKEN,
};

let req = https.request(options, (res) => {
    let data = "";
    res.setEncoding("utf8");
    res.on("data", (d) => {
        data += d;
    });

    res.on("end", () => {
        if (res.statusCode === HTTP_RESPONSE_OK) {
            let resBody = JSON.parse(data);
            // カレンダー一覧が存在する場合に、一覧をコンソールログに出力
            if(resBody.items) {
                // 取得するカレンダーリストの最後2つは「誕生日」と「日本の祝日」カレンダーのため無視する
                for(let i=0, len=resBody.items.length; i < len-2; i++) {
                    console.log(`${(i+1)}${resBody.items[i].summary}`);
                }
            }
        } else {
            // エラー(HTTPレスポンスコード200以外)
            console.log('HTTPレスポンスコード : ' + res.statusCode);
        }
    });
});

req.on("error", (e) => {
    console.log('エラー発生');
});

req.end();

おわりに

GoogleカレンダーAPIだけでもさまざまな機能が提供されています。Google開発者コンソールではAPIに必要なパラメータを入力して実行する環境が提供されているので試しながら実装を進められました。またGoogleAPI関連の投稿ができればと思います。
それではまた令和の時代に。。。

5
6
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
6