Python からAPIで Google Calendar を操作する
目次
進め方
Python Quickstart | Google Calendar API | Google Developers に沿って行う。
手順
プロジェクトの作成
- プロジェクトのプルダウンから新規のプロジェクトを作成
- 新しいプロジェクトから、MyCalendar プロジェクトを作成
Google Calendar API の有効化
- 左のメニューから 有効なAPIとサービス を選択
- APIとサービスの有効化
- 検索バーで Google Calendar API を検索
- 検索結果から Google Calendar API をクリック
- Google Calendar API を有効化
OAuth同意
- スコープ では何も入力せず 保存して次へ
- テストユーザー 自身の Gmailアドレスを追加
- 概要 で結果を確認
認証情報の作成
- 認証情報から CREATE CREDENTIALS をクリック
- OAuthクライアントID を選択
- アプリケーションの種類に デスクトップアプリ を選択
- JSONをダウンロード
pipでライブラリをインストール
# pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
サンプルコードの配置
- Python Quickstart | Google Calendar API | Google Developers
Step 2: Configure the sample
のサンプルコードを保存 SCOPES変数
は実施したい操作により変更が必要- スコープについては Authorizing Requests to the Google Calendar API | Google Developers に記載がある
from __future__ import print_function import datetime import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError # If modifying these scopes, delete the file token.json. SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'] def main(): """Shows basic usage of the Google Calendar API. Prints the start and name of the next 10 events on the user's calendar. """ creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.json', 'w') as token: token.write(creds.to_json()) try: service = build('calendar', 'v3', credentials=creds) # Call the Calendar API now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time print('Getting the upcoming 10 events') events_result = service.events().list(calendarId='primary', timeMin=now, maxResults=10, singleEvents=True, orderBy='startTime').execute() events = events_result.get('items', []) if not events: print('No upcoming events found.') return # Prints the start and name of the next 10 events for event in events: start = event['start'].get('dateTime', event['start'].get('date')) print(start, event['summary']) except HttpError as error: print('An error occurred: %s' % error) if __name__ == '__main__': main()
# ls -l quickstart.py credentials.json -rw-r--r-- 1 root root 406 Aug 20 05:06 credentials.json -rw-r--r-- 1 root root 2611 Aug 20 05:07 quickstart.py
サンプルコードの実行
- サンプルコードの実行
# python /mnt/quickstart.py
- 初回実行時は、ブラウザで認証画面が開く(1つ目はVSCodeから実行した場合の確認画面)
- 続行を選択
- さらに続行を選択
ブラウザに "The authentication flow has completed. You may close this window."と表示される
サンプルコードを実行したターミナルに戻ると、結果が取得されている
Getting the upcoming 10 events 2022-08-23 <予定1> 2022-08-26 <予定2> 2022-08-26 <予定3> 2022-09-17 <予定4> 2022-09-18 <予定5> 2022-10-08 <予定6> 2022-10-18 <予定7> 2022-10-22 <予定8> 2022-11-18 <予定9> 2022-12-18 <予定10>
# ls -l quickstart.py credentials.json token.json -rw-r--r-- 1 root root 406 Aug 20 05:06 credentials.json -rw-r--r-- 1 root root 2611 Aug 20 05:07 quickstart.py -rw-r--r-- 1 root root 650 Aug 21 11:24 token.json