'Attribute Error When Using API to Access Google Calendar

I wrote some basic code to test the Google Calendar API using delegated credentials:

credentials = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)
credentials = credentials.with_subject(SUBJECT_EMAIL)
calendar_service = googleapiclient.discovery.build('calendar', 'v3', credentials)
events = calendar_service.events().list(calendarId='primary').execute()

I get an error AttributeError: 'Credentials' object has no attribute 'request' which is triggered on the last line.

I've run similar code many times in the past and haven't ever come across this issue. Any help would be appreciated.

Here is the traceback:

Traceback (most recent call last):
  File "/Users/jd/PycharmProjects/TorOooCalendarIntegration/main.py", line 14, in <module>
    events = calendar_service.events().list(calendarId='primary').execute()
  File "/Users/jd/PycharmProjects/TorOooCalendarIntegration/venv/lib/python3.10/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/Users/jd/PycharmProjects/TorOooCalendarIntegration/venv/lib/python3.10/site-packages/googleapiclient/http.py", line 920, in execute
    resp, content = _retry_request(
  File "/Users/jd/PycharmProjects/TorOooCalendarIntegration/venv/lib/python3.10/site-packages/googleapiclient/http.py", line 191, in _retry_request
    resp, content = http.request(uri, method, *args, **kwargs)
AttributeError: 'Credentials' object has no attribute 'request'


Solution 1:[1]

Try this is insead.

import httplib2
import pprint
import sys

from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

def main(argv):
  # Load the json format key that you downloaded from the Google API     
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      SERVICE_ACCOUNT_FILE,
      scopes=SCOPES)
  credentials = credentials.with_subject(SUBJECT_EMAIL)

  # Create an httplib2.Http object to handle our HTTP requests and authorize
  # it with the Credentials.
  http = httplib2.Http()
  http = credentials.authorize(http)

  service = build("calendar", "v3", http=http)

  # List all the tasklists for the account.
  events = service.events().list(calendarId='primary').execute(http=http)
  pprint.pprint(events)


if __name__ == '__main__':
  main(sys.argv)

Shamelessly copied and altered from tasks.py

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DaImTo