Installation and Initialization¶
Once you have your credentials, you can install the package with:
pip install easy-google-docs
Importing and authentication¶
Using JSON File¶
Knowing where your credentails.json file is, you can initialize and authenticate with:
from easygoogledocs import GoogleAPI, AUTH_TYPE_BROWSER, AUTH_TYPE_SERVICE_ACCOUNT
api = GoogleAPI(credentials_file='credentials.json')
# To authorize with a web-browser based OAuth Token:
api.authorize(authentication_type=AUTH_TYPE_BROWSER)
# To authorize with a service account:
api.authorize(authentication_type=AUTH_TYPE_SERVICE_ACCOUNT)
Using JSON Object¶
Recommended for production deployment. In this case, we don’t want to store our private key and ID in the JSON file, especially in plain text (and especially in a code repository!). In this case, we can load in the content of the JSON file (which has had the private key and ID fields stripped) and add them in using environment variables:
import json
from easygoogledocs import GoogleAPI, AUTH_TYPE_BROWSER, AUTH_TYPE_SERVICE_ACCOUNT
# load the cleaned JSON credentials file
json_auth_file = open('myproject-creds-clean.json', 'r')
json_credentials = json.loads(json_auth_file.read())
json_auth_file.close()
# update the private key ID from an environment variable
json_credentials['private_key_id'] = os.getenv('GOOGLE_API_PRIVATE_KEY_ID')
# note: in some cases (GitHub stored secrets, for example) the `\n` character is stored with an escaped backslash,
# so we need to clean this up as we load the private key, or authentication won't work.
json_credentials['private_key'] = os.getenv('GOOGLE_API_PRIVATE_KEY').replace('\\n', '\n')
# instead of using the `credentials_file` parameter, we can use the `credentials_json` and pass in our JSON object
api = GoogleAPI(credentials_json=json_credentials)
# To authorize with a web-browser based OAuth Token:
api.authorize(authentication_type=AUTH_TYPE_BROWSER)
# To authorize with a service account:
api.authorize(authentication_type=AUTH_TYPE_SERVICE_ACCOUNT)