intermittent error while calling GMAIL API - "The caller does not have permission"

Viewed 389

getting this error intermittently

HttpError 403 when requesting https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest returned "The caller does not have permission"

It works sometimes and other times it doesn't. I see the same issue on the oauth2 playground

this is my code -

googlecredentials = GoogleCredentials(
    access_token=None,
    client_id='xxx',
    client_secret='xxxx',
    refresh_token='xxxx',
    token_expiry=None,
    token_uri="https://www.googleapis.com/oauth2/v3/token", 
    user_agent='Python client library'
)

service = build('gmail', 'v1', credentials=googlecredentials)

results = service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])
response = service.users().messages().list(userId='me', q='subject:FDA').execute()
print(response)
2 Answers

I was also facing this issue came very recently. I have been using GMAIL API for more than a year now and I have never faced this issue. I don't know if there is an issue from our side or Gmail changed their policy of usage. But, regardless I did manage to find the solution for it. The main issue that I was having was my creds (google credentials in your case) was getting expired and each time it was expired I had to refresh them. So, a simple solution would be to just refresh them.

if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())

My native language is python so I have written the code in the same language but you can head over here and see something similar in your native language

Thank you.

I am also seeing this all of a sudden. Everything was working fine for many months nothing changed in the code. Also seeing the token is getting refreshed.

-rw-r--r-- 1 kosalanbalarajah staff 728 Jul 6 12:50 token.pickle

But the error does not get resolved.

Also has the refresh code since the begining.

If there are no (valid) credentials available, let the user log in.

    # If token.pickle does not exist there are no valid token, let user log in again to generate token and save the token for furture use.
    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(credentialspath, self.SCOPES) # Change credentials.json to credentialspath
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open(tokenpath, 'wb') as token: # Change token.pickle to tokenpath
            pickle.dump(creds, token)

    return creds
Related