I have a Python application that accesses Youtube-Data-API v3.
After the program runs for an hour, it throws an error suggesting the access token has expired.
How can I persist the token for a longer period?
There is now way to extend the time for access token
. They get expired after an hour. The only way of using a token is to get a new token using refresh_token
provided by the api.
First you get offline token by setting access_type
to offine
while authenticating the user.
{
'response_type': 'code',
'client_id': 'client_id',
'redirect_uri': '...',
'access_type':'offline',
'scope': 'https://www.googleapis.com/auth/youtube.readonly',
}
you will get refresh_token
, access_token
, id_token
along with expiry
and some other fields which you can save in you database and fetch later when needed.
Before using the access_token
you check if it is valid
creds = google.oauth2.credentials.Credentials(access_token,refresh_token=refresh_token,id_token=id_token,token_uri=token_uri,client_id=client_id,client_secret=client_secret,scopes=scopes,expiry=expirytime)
if creds.valid == False:
// Refresh to get the new token
req =google.auth.transport.requests.Request()
creds.refresh(req)
// Now Save new Credentials from "creds" so that you can use later.
After verifying the access_token
you can now query youtube data api
requests
youtube = googleapiclient.discovery.build(
"youtube", "v3",credentials=creds)
req = youtube.videos().getRating(id="xxxxxxxxx")
resp =req.execute()