I've been grappling with an issue for weeks while trying to run an app that utilizes Google APIs with OAuth in Python through a headless linux server. I've tried to do this the easy way using Oauth packages but Google's APIs don't accept commonly passed arguments by these functions. That issue is documented here.
I've instead tried to follow an example on Google's documentation page which makes use of Flask to create and return the credentials. I've attempted to make my own webpage that will simply return the credentials in JSON format:
@app.route('/credentials')
def get_credentials():
if 'credentials' not in flask.session:
return flask.redirect('authorize')
#oauth_refresh = OAuth2Session(client_id, token=token)
# Load credentials from the session.
credentials = google.oauth2.credentials.Credentials(
**flask.session['credentials'])
creds_dict = {'token': credentials.token,
'refresh_token': credentials.refresh_token,
'token_uri': credentials.token_uri,
'client_id': credentials.client_id,
'client_secret': credentials.client_secret,
'scopes': credentials.scopes}
creds_dict = jsonify(creds_dict)
return creds_dict
if __name__ == '__main__':
# When running locally, disable OAuthlib's HTTPs verification.
# ACTION ITEM for developers:
# When running in production *do not* leave this option enabled.
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1'
# Specify a hostname and port that are set as a valid redirect URI
# for your API project in the Google API Console.
app.run('localhost', 8080, debug=True)
And then I try to use requests to simply grab the result of this data so I can proceed with creating the Google service:
res = requests.get("http://localhost:8080/credentials")
cred = res.json()
service = build(API_SERVICE_NAME, API_VERSION, credentials=cred)
However, the .json() line always results in
json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 1)
Because this is returning text/html not JSON, despite me explicitly making the flask function return JSON. I've tried multiple solutions such as this to no avail. You can take a look at the random HTML generated instead here.