Search code examples
python-3.xgoogle-cloud-platformgoogle-cloud-functionsgoogle-cloud-storageservice-accounts

Cloud function attribute error: 'bytes' object has no attribute 'get' when reading json file from cloud storage


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


Solution

  • 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'])