Search code examples
pythongoogle-apigoogle-cloud-platformautomlgoogle-cloud-automl

Generating Bearer Token for AutoML, Computer Vision from Python Library


Based on this Google documentation I can generate the token for Computer Vision API request by calling this in terminal gcloud auth application-default print-access-token. However, I am going to call the request from my python code and I try to generate from Python code, something like below...

The code is based on this documentation page

with open( environ.get(KEY_ENV_VARIABLE) ) as f:
    key = json.load(f)

iat = time.time()
exp = iat + 3600
payload = {
    'iss': key.get('client_email'),
    'sub': key.get('client_email'),
    'aud': 'https://vision.googleapis.com/google.cloud.automl_v1beta1',
    'iat': iat,
    'exp': exp
}
additional_headers = { "kid": key.get("private_key_id") }
signed_jwt = jwt.encode(payload, key.get("private_key"), headers=additional_headers, algorithm='HS256')
return signed_jwt.decode('utf-8')

It does generate the token however it is different in terms of length, compared to the token generated by gcloud tool.

I know that the easiest and quick dirty fix would be calling os.system('gcloud auth application-default print-access-token'). However, I do not want to do the dirty way if possible and want to generate the token in correct way.


Solution

  • Try following this documentation to download a service account. After you get a key, you'll want to set GOOGLE_APPLICATION_CREDENTIALS to the file path of the key.