クイックスタートでは、Google Workspace API を呼び出すアプリを設定して実行する方法について説明します。このクイックスタートでは、テスト環境に適した簡略化された認証方法を使用します。本番環境では、アプリに適したアクセス認証情報を選択する前に、認証と認可について学習することをおすすめします。
Drive Labels API にリクエストを行う Python コマンドライン アプリケーションを作成します。
目標
- 環境をセットアップする。
- クライアント ライブラリをインストールする。
- サンプルを設定します。
- サンプルを実行します。
前提条件
- Python 2.6 以降
- pip パッケージ管理ツール
- Google Cloud プロジェクト。
- Google アカウント。
環境の設定
このクイックスタートを完了するには、環境を設定します。
API を有効にする
Google API を使用する前に、Google Cloud プロジェクトで API を有効にする必要があります。1 つの Google Cloud プロジェクトで 1 つ以上の API を有効にできます。Google Cloud コンソールで、ドライブ ラベル API を有効にします。
デスクトップ アプリケーションの認証情報を承認する
エンドユーザーを認証してアプリ内のユーザーデータにアクセスするには、1 つ以上の OAuth 2.0 クライアント ID を作成する必要があります。クライアント ID は、Google の OAuth サーバーで個々のアプリを識別するために使用します。アプリが複数のプラットフォームで実行される場合は、プラットフォームごとに個別のクライアント ID を作成する必要があります。- Google Cloud コンソールで、メニュー > > [クライアント] に移動します。
- [Create Client] をクリックします。
- [アプリケーション タイプ] > [デスクトップ アプリ] をクリックします。
- [名前] フィールドに、認証情報の名前を入力します。この名前は Google Cloud コンソールにのみ表示されます。
- [Create] をクリックします。
新しく作成した認証情報は、[OAuth 2.0 クライアント ID] に表示されます。
- ダウンロードした JSON ファイルを
credentials.json
として保存し、作業ディレクトリに移動します。
Google クライアント ライブラリをインストールする
Python 用 Google クライアント ライブラリをインストールします。
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
代替のインストール オプションについては、Python ライブラリのインストール セクションをご覧ください。
サンプルを構成する
- 作業ディレクトリに
quickstart.py
という名前のファイルを作成します。 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()
サンプルの実行
作業ディレクトリで、サンプルをビルドして実行します。
python quickstart.py
サンプルを初めて実行すると、アクセス権限の承認を求めるメッセージが表示されます。
- Google アカウントにログインしていない場合は、ログインを求められます。複数のアカウントにログインしている場合は、承認に使用するアカウントを 1 つ選択します。
- [Accept] をクリックします。
承認情報はファイル システムに保存されるため、次回サンプルコードを実行するときに承認を求められることはありません。
これで、Drive Labels API にリクエストを行う最初の Python アプリケーションが正常に作成されました。