How to auto refresh Google calendar token in python


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 =
today_date = str(today[:10])

url = f'****Calendar_ID****/events?maxResults=99999&access_type=offline&approval_prompt=force&key={API_KEY}'

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

params= {
    "access_type" : "offline",
    "approval_prompt" : "force"

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

Asked By: User1



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:
        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:

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.




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