背景
- REST APIでGoogle Cloud APIsを実行したいので、Access Token が欲しい
- 例
curl -X POST \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
--data "{
'config': {...}
}" "https://speech.googleapis.com/v1p1beta1/speech:longrunningrecognize"
- 例えば、CloudFunction上で、python経由でshell実行
gcloud auth application-default print-access-token
してもaccess tokenは取得できなくて困る(空文字が返る) - Pythonだけで上でAccess Tokenを取得したい
実装
getting_access_token_with_python
import google.auth
import google.auth.transport.requests
credentials, your_project_id = google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
auth_req = google.auth.transport.requests.Request()
credentials.refresh(auth_req) #refresh token
print(credentials.token) # prints token
これだと、CloudFunctionからでもAccessTokenが取得できた。