背景
- Google検索して上位に出てくる結果がネット上のサンプルコードがユーザのOAuth認証を前提としている。(GCP公式ドキュメント含め)
- アプリケーション側から直接コールさせるので、サービスアカウントを利用したい。
- ref:
Python with Google Sheets Service Account: Step by Step | Medium
手順
- GCPコンソール上でサービスアカウント作成
- サービスアカウントに紐づくAPIアクセス用の credential をGCPから保存 (例:
credential.json
) - service accountのemailアドレスを任意のspreadsheetに共有設定する
- 以下のコマンド群を書き込む
# install
# pip install --upgrade google-api-python-client oauth2client
import httplib2
import os
from apiclient import discovery
from google.oauth2 import service_account
# configure
scopes = ['https://www.googleapis.com/auth/spreadsheets.readonly']
secret_file = os.path.join(os.getcwd(), 'credential.json')
credentials = service_account.Credentials.from_service_account_file(secret_file, scopes=scopes)
service = discovery.build('sheets', 'v4', credentials=credentials)
# spreadsheet
spreadsheet_id = '1EoBDbH7QRVS5F8O7YNAiKWMzETLkNU6wIKKCJSSItnuS'
result = service.spreadsheets().values().get(spreadsheetId=spreadsheet_id, range="'シート1'!A1:AC767").execute()
values = result.get('values', [])
おわり
Jupyter Notebook 等からでもこの数行で動かせます