How to auto refresh Google calendar token in python

Question:

I’m using the following script in order to get all today’s events from a specific google calendar. the code works for me.
The only thing is that the token expires after ~60 min.

How can I make the token refresh automatically?

import requests
import json
import datetime

API_KEY = "******************"

today = datetime.datetime.now().isoformat()
today_date = str(today[:10])


url = f'https://www.googleapis.com/calendar/v3/calendars/****Calendar_ID****/events?maxResults=99999&access_type=offline&approval_prompt=force&key={API_KEY}'


headers = {
  'Authorization': 'Bearer *********************************************************'
}

params= {
    "timeMin":f"{today_date}T00:00:00-06:00",
    "timeMax":f"{today_date}T23:59:59-06:00",
    "access_type" : "offline",
    "approval_prompt" : "force"
}

response = requests.request("GET", url, headers=headers, params=params)

print(response.text)
Asked By: User1

||

Answers:

The reason it only works for an hour is that your access token is expiring.

If you follow the official python sample you will notice that it stores the user credentials in a file. It then loads the refresh token when ever it needs to request a new access token

if os.path.exists('token.json'):
    creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            'credentials.json', SCOPES)
        creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open('token.json', 'w') as token:
        token.write(creds.to_json())

In your case you are hard coding the access token, so its hard to tell how you are creating that in the first place. What ever system creates that for you will need to request offline access and get a refresh token back. Once you have that refresh token you can use it to request a new access token.

Code:

POST https://accounts.google.com/o/oauth2/token
client_id={ClientId}.apps.googleusercontent.com&client_secret={ClientSecret}&refresh_token=1/ffYmfI0sjR54Ft9oupubLzrJhD1hZS5tWQcyAvNECCA&grant_type=refresh_token

Response

{
"access_token" : "ya29.1.AADtN_XK16As2ZHlScqOxGtntIlevNcasMSPwGiE3pe5ANZfrmJTcsI3ZtAjv4sDrPDRnQ",
"token_type" : "Bearer",
"expires_in" : 3600
}
Answered By: DaImTo