Search code examples
python-2.7gmail-api

403 "Request had insufficient authentication scopes" when creating drafts in Google API with Python


I am working with the google api for the first time, and am new to coding in general, and have a question that I'm sure is very simple, but I cannot find the answer to. When I run the following code -

credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)

results = service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])

if not labels:
    print('No labels found.')
else:
    print('Labels:')
    for label in labels:
        print(label['name'])


message_body = "This is the message"

message = {'message': message_body}

draft = service.users().drafts().create(userId='me', body=message).execute()

I am successfully able to list the labels in my gmail account, but the request to create a draft kicks back an error message "Request had insufficient authentication request". I found that creating drafts requires one of the following scopes:

but for the life of me, I cannot figure out what exactly that means or how to make that happen, though I've done my best to find this somewhere.


Solution

  • You probably have a global variable SCOPES in you code with the value of https://www.googleapis.com/auth/gmail.readonly if you are following the Quickstart. These scopes are used when your users are redirected to Google in order to give you an access_token so you can read the contents of your user's gmail account.

    In order to send drafts etc. you need one of the scopes you mentioned, e.g. https://mail.google.com/. Change your value of SCOPES to this string, and remove your credentials located at ~/.credentials/gmail-python-quickstart.json as outlined by the Quickstart in order to get new credentials that can do more than just read content.