Skip to content

Instantly share code, notes, and snippets.

@clarketm
Last active August 30, 2023 19:42
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save clarketm/dc5d5be390e3f811a2dd7f5e8c5728ba to your computer and use it in GitHub Desktop.
Save clarketm/dc5d5be390e3f811a2dd7f5e8c5728ba to your computer and use it in GitHub Desktop.
How to get Google OAuth 2.0 access token in console using the Python API
#!/usr/bin/env python
'''
This script will attempt to open your webbrowser,
perform OAuth 2.0 authentication and print your access token.
To install dependencies from PyPI:
$ pip install oauth2client
Then run this script:
$ python get_oauth2_token.py
This is a combination of snippets from:
https://developers.google.com/api-client-library/python/guide/aaa_oauth
https://gist.github.com/burnash/6771295
'''
import os, sys
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run_flow
from oauth2client.file import Storage
def return_token():
return get_oauth2_token();
def disable_stout():
o_stdout = sys.stdout
o_file = open(os.devnull, 'w')
sys.stdout = o_file
return (o_stdout, o_file)
def enable_stout(o_stdout, o_file):
o_file.close()
sys.stdout = o_stdout
def get_oauth2_token():
CLIENT_ID = '<Client ID from Google API Console>'
CLIENT_SECRET = '<Client secret from Google API Console>'
SCOPE = '<OAuth 2.0 scope>'
REDIRECT_URI = '<Redirect URI from Google API Console>'
o_stdout, o_file = disable_stout()
flow = OAuth2WebServerFlow(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
scope=SCOPE,
redirect_uri=REDIRECT_URI)
storage = Storage('creds.data')
credentials = run_flow(flow, storage)
enable_stout(o_stdout, o_file)
print "access_token: %s" % credentials.access_token
if __name__ == '__main__':
return_token()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment