Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 446
Aman Bedi Avatar asked Jul 03 '20 14:07

Aman Bedi


1 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.

like image 177
Killmonger Avatar answered Nov 19 '22 05:11

Killmonger