Article
Hack of the week #11 – GOOGLE API OAuth 2.0
27/6/22
Inovácie a vývoj
Article
Hack of the week #11 – GOOGLE API OAuth 2.0
Inovácie a vývoj
June 27, 2022
Hack of the week #11 – GOOGLE API OAuth 2.0
Inovácie a vývoj
June 27, 2022
Article
Hack of the week #11 – GOOGLE API OAuth 2.0
Inovácie a vývoj
June 27, 2022
In this article I am going to present necessary steps for authenticating for Google services. Prerequisite is service created on google cloud console.
In this article I am going to present necessary steps for authenticating for Google services. Prerequisite is service created on google cloud console. https://console.cloud.google.com/ and secondly client_secret_file.json which creation is described below.
Once service is there, enabling type of API is required. In our case we are aiming to working within Google drive workspace. We can easily enable google drive API in library section using search and enable button.
Next step is creating OAuth credentials. We can create credential file from credentials section of the project. Clicking on create and create OAuth client ID. After successful creation the console should look like this.
Now we are able to download and store the json credentials as client_secret_file.json for later use.
Authenticating to google API consists basically from two main steps:
- creating token from existing client secret
- refreshing token
Let's see some code behind.
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
SCOPES = ['https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/spreadsheets']
flow = InstalledAppFlow.from_client_secrets_file(config.client_secret_file_path, SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open(config.token_pickle_file, 'wb') as token:
pickle.dump(creds, token)
This sequence is triggered only as first run. In next run we need to check whether token exist and if valid. If not, just refresh.
if os.path.exists(token_pickle):
with open(token_pickle, 'rb') as token:
creds = pickle.load(token)if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else: # Use previous code to save token as a pickle :)
And now we are ready to create session with google.
self.DRIVE = build('drive', 'v3', credentials=creds, cache_discovery=False)
Once session is created, we are free to use API.
file_metadata = {'name': filename, 'mimeType': 'application/vnd.ms-excel'}
media = MediaFileUpload(file_source_path, mimetype='application/vnd.ms-excel')
file = self.DRIVE.files().create(body=file_metadata,
media_body=media, fields='id').execute()
In the example above we have just uploaded excel file to google drive. On return in file variable you can get file ID which could be use for later manipulation.
More in my next HACK OF WEEK :)