Python クイックスタート

クイックスタートでは、Google Workspace API を呼び出すアプリを設定して実行する方法について説明します。

Google Workspace クイックスタートでは、API クライアント ライブラリを使用して認証と認可のフローの詳細を処理します。独自のアプリでは、クライアント ライブラリを使用することをおすすめします。このクイックスタートでは、テスト環境に適した簡素化された認証方法を使用します。本番環境では、アプリに適したアクセス認証情報を選択する前に、認証と認可について確認することをおすすめします。

Google Calendar API にリクエストを送信する Python コマンドライン アプリケーションを作成します。

目標

  • 環境を設定する。
  • クライアント ライブラリをインストールする。
  • サンプルをセットアップします。
  • サンプルを実行します。

Prerequisites

このクイックスタートを実行するには、次の前提条件を満たす必要があります。

  • Google カレンダーが有効になっている Google アカウント。

環境をセットアップする

このクイックスタートを完了するには、環境を設定します。

API を有効にする

Google API を使用するには、事前に Google Cloud プロジェクトで API を有効にする必要があります。1 つの Google Cloud プロジェクトで 1 つ以上の API を有効にできます。
  • Google Cloud コンソールで、Google Calendar API を有効にします。

    API の有効化

新しい Google Cloud プロジェクトを使用してこのクイックスタートを行う場合は、OAuth 同意画面を構成して、自分自身をテストユーザーとして追加します。Cloud プロジェクトでこの手順をすでに完了している場合は、次のセクションに進んでください。

  1. Google Cloud コンソールで、メニュー > [API とサービス] > [OAuth 同意画面] に移動します。

    OAuth 同意画面に移動

  2. アプリのユーザータイプを選択し、[作成] をクリックします。
  3. アプリ登録フォームに入力し、[保存して次へ] をクリックします。
  4. 現時点では、スコープの追加をスキップして、[Save and Continue] をクリックします。今後、Google Workspace 組織の外部で使用するアプリを作成する場合は、アプリに必要な認可スコープを追加して確認する必要があります。

  5. ユーザーの種類に [外部] を選択した場合は、テストユーザーを追加します。
    1. [テストユーザー] で [ユーザーを追加] をクリックします。
    2. メールアドレスとその他の承認済みテストユーザーを入力し、[保存して次へ] をクリックします。
  6. アプリ登録の概要を確認します。変更するには、[Edit] をクリックします。アプリの登録に問題がなければ、[Back to Dashboard] をクリックします。

デスクトップ アプリケーションの認証情報を承認する

エンドユーザーとして認証し、アプリ内でユーザーデータにアクセスするには、1 つ以上の OAuth 2.0 クライアント ID を作成する必要があります。クライアント ID は、Google の OAuth サーバーで 1 つのアプリを識別するために使用されます。アプリを複数のプラットフォームで実行する場合は、プラットフォームごとに個別のクライアント ID を作成する必要があります。
  1. Google Cloud コンソールで、メニュー > [API とサービス] > [認証情報] に移動します。

    [認証情報] に移動

  2. [認証情報を作成] > [OAuth クライアント ID] をクリックします。
  3. [アプリケーションの種類] > [デスクトップ アプリ] をクリックします。
  4. [名前] フィールドに、認証情報の名前を入力します。この名前は Google Cloud コンソールにのみ表示されます。
  5. [作成] をクリックします。OAuth クライアントの作成画面が表示され、新しいクライアント ID とクライアント シークレットが表示されます。
  6. [OK] をクリックします。新しく作成された認証情報が [OAuth 2.0 クライアント ID] に表示されます。
  7. ダウンロードした JSON ファイルを credentials.json として保存し、ファイルを作業ディレクトリに移動します。

Google クライアント ライブラリをインストールする

  • Python 用 Google クライアント ライブラリをインストールします。

    pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
    

サンプルを構成する

  1. 作業ディレクトリに quickstart.py という名前のファイルを作成します。
  2. quickstart.py に次のコードを追加します。

    Calendar/quickstart/quickstart.py
    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()

サンプルの実行

  1. 作業ディレクトリでサンプルをビルドして実行します。

    python3 quickstart.py
    
  2. サンプルを初めて実行すると、アクセスの承認を求めるプロンプトが表示されます。

    1. Google アカウントにまだログインしていない場合は、ログインを求められます。複数のアカウントにログインしている場合は、承認に使用するアカウントを 1 つ選択します。
    2. [承認] をクリックします。

    承認情報はファイル システムに保存されるため、次回サンプルコードを実行するときは承認を求められません。

Google Calendar API にリクエストを送信する最初の Python アプリケーションが正常に作成されました。

次のステップ