2

I'm trying to read a JSON key file from Google Cloud Storage to authenticate. I have the following function:

storage_client = storage.Client()
bucket_name = 'bucket_name'
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.get_blob('key.json')
json_data_string = blob.download_as_string()

credentials = ServiceAccountCredentials.from_json_keyfile_dict(
    json_data_string,
    scopes=['https://www.googleapis.com/auth/analytics',
            'https://www.googleapis.com/auth/analytics.edit'])

and the following error: AttributeError: 'bytes' object has no attribute 'get'

How should I read/format my key.json file to use it with ServiceAccountCredentials

Dustin Ingram
  • 20,502
  • 7
  • 59
  • 82
Simon Breton
  • 2,638
  • 7
  • 50
  • 105

1 Answers1

2

The download_as_string() function returns bytes, but from_json_keyfile_dict() expects a dict. You need to first decode the bytes to turn it into a string:

json_data_string = blob.download_as_string().decode('utf8')

And then load this string as a dict:

import json
json_data_dict = json.loads(json_data_string)

And then you can call:

credentials = ServiceAccountCredentials.from_json_keyfile_dict(
    json_data_dict,
    scopes=['https://www.googleapis.com/auth/analytics',
            'https://www.googleapis.com/auth/analytics.edit'])
Dustin Ingram
  • 20,502
  • 7
  • 59
  • 82
  • What are bytes exactly? Is there a way to directly access json file from storage in the proper format? – Simon Breton Feb 10 '20 at 19:10
  • See https://stackoverflow.com/questions/10060411/byte-string-vs-unicode-string-python. The "proper format" is subjective here, Cloud Storage just stores binary blobs, so it's up to you to turn it into the format you're expecting it to be. – Dustin Ingram Feb 10 '20 at 19:13
  • Ok. so whatever I extract from Cloud Storage it will always be binary blobs. – Simon Breton Feb 10 '20 at 19:17