Python のクイックスタート

クイックスタートでは、 Google Workspace API

Google Workspace クイックスタートでは、API クライアント ライブラリを使用して 認証と認可のフローの詳細を確認できます。おすすめの方法 独自のアプリ用のクライアント ライブラリを使用します。このクイックスタートでは、 テストに適したシンプルな認証アプローチ できます。本番環境では、Terraform の IAM 構成の 認証と認可 次の日付より前 アクセス認証情報の選択 選択することもできます

Google Apps Script API にリクエストを行う Python コマンドライン アプリケーションを作成する。

目標

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

前提条件

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

  • Google ドライブが有効になっている Google アカウント。

環境の設定

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

API を有効にする

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

    API の有効化

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

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

    OAuth 同意画面に移動

  2. [ユーザーの種類] で [内部] を選択し、[作成] をクリックします。
  3. アプリ登録フォームに入力し、[保存して次へ] をクリックします。
  4. 現時点では、スコープの追加をスキップして [保存して次へ] をクリックします。 今後、Google Play 以外で使用するアプリを作成した場合、 [ユーザーの種類] を [外部] に変更してから、 アプリに必要な認証スコープを追加します。

  5. アプリ登録の概要を確認します。変更するには、[編集] をクリックします。アプリが 問題がなければ、[ダッシュボードに戻る] をクリックします。

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

エンドユーザーを認証してアプリでユーザーデータにアクセスするには、次のことを行う必要があります。 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
    

サンプルを構成する

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

    apps_script/quickstart/quickstart.py
    """
    Shows basic usage of the Apps Script API.
    Call the Apps Script API to create a new script project, upload a file to the
    project, and log the script's URL to the user.
    """
    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 import errors
    from googleapiclient.discovery import build
    
    # If modifying these scopes, delete the file token.json.
    SCOPES = ["https://www.googleapis.com/auth/script.projects"]
    
    SAMPLE_CODE = """
    function helloWorld() {
      console.log("Hello, world!");
    }
    """.strip()
    
    SAMPLE_MANIFEST = """
    {
      "timeZone": "America/New_York",
      "exceptionLogging": "CLOUD"
    }
    """.strip()
    
    
    def main():
      """Calls the Apps Script API."""
      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("script", "v1", credentials=creds)
    
        # Call the Apps Script API
        # Create a new project
        request = {"title": "My Script"}
        response = service.projects().create(body=request).execute()
    
        # Upload two files to the project
        request = {
            "files": [
                {"name": "hello", "type": "SERVER_JS", "source": SAMPLE_CODE},
                {
                    "name": "appsscript",
                    "type": "JSON",
                    "source": SAMPLE_MANIFEST,
                },
            ]
        }
        response = (
            service.projects()
            .updateContent(body=request, scriptId=response["scriptId"])
            .execute()
        )
        print("https://script.google.com/d/" + response["scriptId"] + "/edit")
      except errors.HttpError as error:
        # The API encountered a problem.
        print(error.content)
    
    
    if __name__ == "__main__":
      main()

サンプルの実行

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

    python3 quickstart.py
    
  1. サンプルを初めて実行すると、アクセスの承認を求められます。 <ph type="x-smartling-placeholder">
      </ph>
    1. Google アカウントにまだログインしていない場合は、ログインを求められたらログインします。条件 複数のアカウントにログインしている場合は、承認に使用するアカウントを 1 つ選択してください。
    2. [Accept] をクリックします。

    Python アプリケーションが実行され、Google Apps Script API が呼び出されます。

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

次のステップ