Sample code for 30+ languages & platforms
Python Requires Chilkat v11.0.0+

Refresh a Gmail OAuth access token

See more GMail REST API Examples

Use the refresh token and the same Desktop app client that issued it. Run in the private directory used by the authorization example. Preserve the refresh token if Google omits it from the response. Refreshing continues the existing grant. Request additional scopes through interactive authorization.

Google documentation

Chilkat Python Downloads

Python
import sys
import chilkat2

success = False

# Assumes Chilkat is unlocked. See Global Unlock Sample.

token = chilkat2.JsonObject()
success = token.LoadFile("gmail-token.json")
if (success != True):
    print("Could not read gmail-token.json from the private working directory.")
    sys.exit()

if ((token.JsonTypeOf("refresh_token") != 1) or (token.StringOfEquals("refresh_token","",True) == True)):
    print("Authorize the account for offline access first.")
    sys.exit()

oauth = chilkat2.OAuth2()
oauth.TokenEndpoint = "https://oauth2.googleapis.com/token"
oauth.ClientId = "YOUR_DESKTOP_CLIENT_ID"
oauth.ClientSecret = "YOUR_DESKTOP_CLIENT_SECRET"
oauth.RefreshToken = token.StringOf("refresh_token")
success = oauth.RefreshAccessToken()
if (success != True):
    print("Refresh failed. Check the OAuth client and grant. A revoked or expired grant requires fresh consent.")
    sys.exit()

fresh = chilkat2.JsonObject()
success = fresh.Load(oauth.AccessTokenResponse)
if (success != True):
    print("Could not parse the refresh response.")
    sys.exit()

if ((fresh.JsonTypeOf("access_token") != 1) or (fresh.StringOfEquals("access_token","",True) == True)):
    print("The refresh response did not contain an access token.")
    sys.exit()

if ((fresh.JsonTypeOf("refresh_token") != 1) or (fresh.StringOfEquals("refresh_token","",True) == True)):
    fresh.UpdateString("refresh_token",token.StringOf("refresh_token"))

if ((fresh.HasMember("scope") != True) and (token.JsonTypeOf("scope") == 1)):
    fresh.UpdateString("scope",token.StringOf("scope"))

success = fresh.WriteFile("gmail-token.json")
if (success != True):
    print("Could not save the refreshed credentials.")
    sys.exit()

print("Refreshed the access token.")