症状
あたりを参考に、Googleスプレッドシートをpythonからいじろうとしたらハマった。
- macOS High Sierra 10.13.4
- python 3.6
- gspread 3.0.0
- oauth2client 4.1.2
ソースコードはSCUEL開発者ブログのほぼそのままなので割愛。
エラーメッセージ
Traceback (most recent call last):
File "/Users/****/testspread.py", line 22, in <module>
wks = gc.open("idcard").sheet1
File "/Users/****/myenv/lib/python3.6/site-packages/gspread/client.py", line 122,in open
self.list_spreadsheet_files()
File "/Users/****/myenv/lib/python3.6/site-packages/gspread/client.py", line 96, in list_spreadsheet_files
res = self.request('get', url, params=params).json()
File "/Users/****/myenv/lib/python3.6/site-packages/gspread/client.py", line 79, in request
raise APIError(response)
gspread.exceptions.APIError: {
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission"
}
],
"code": 403,
"message": "Insufficient Permission"
}
}
Insufficient Permission なので認証が通っていない??
- Google Drive APIを有効化
- サービスアカウントを作成して、編集権限を追加
- APIアクセスのJSONファイルをダウンロード
- 操作したいスプレッドシートに、共有編集者として作成したサービスアカウントを追加
はちゃんとやったはず。
検索
gspread Insufficient Permission python
でググったら
ここが見つかって
insufficient permission · Issue #532 · burnash/gspread · GitHub
ここにたどり着いた。
python - gspread authentication throwing insufficient permission - Stack Overflow
解決
Google Drive API のほかに、Google Sheets API を有効にし、
before
scope = ['https://spreadsheets.google.com/feeds']
を
after
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
にしたら動いた。
その後
公式リファレンス見たら書いてあったというオチ
gspread API Reference — gspread 3.0.0 documentation

ドキュメントは良く読みましょう!