Python のクイックスタート

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

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

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

目標

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

前提条件

  • Google アカウント

環境の設定

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

API を有効にする

Google API を使用する前に、Google Cloud プロジェクトで API を有効にする必要があります。1 つの Google Cloud プロジェクトで 1 つ以上の API を有効にできます。

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

エンドユーザーを認証し、アプリ内でユーザーデータにアクセスするには、1 つ以上の OAuth 2.0 クライアント ID を作成する必要があります。クライアント ID は、Google の OAuth サーバーで個々のアプリを識別するために使用します。アプリを複数のプラットフォームで実行する場合は、プラットフォームごとに個別のクライアント 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
    

その他のインストール オプションについては、Python ライブラリのインストールのセクションをご覧ください。

サンプルを構成する

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

    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/drive.labels.readonly']
    
    def main():
      """Shows basic usage of the Drive Labels API.
    
        Prints the first page of the customer's Labels.
      """
      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('drivelabels', 'v2', credentials=creds)
        response = service.labels().list(
            view='LABEL_VIEW_FULL').execute()
        labels = response['labels']
    
        if not labels:
          print('No Labels')
        else:
          for label in labels:
            name = label['name']
            title = label['properties']['title']
            print(u'{0}:\t{1}'.format(name, title))
      except HttpError as error:
        # TODO (developer) - Handle errors from Labels API.
        print(f'An error occurred: {error}')
    
    if __name__ == '__main__':
      main()
    

サンプルの実行

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

    python quickstart.py
    
  2. サンプルを初めて実行すると、アクセスの承認を求められます。

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

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

Drive Labels API にリクエストを送信する最初の Python アプリケーションを作成できました。

次のステップ