Back to snippets

google_calendar_api_oauth_list_upcoming_events.py

python

A command-line application that lists the next 10 events on the user

19d ago70 linesdevelopers.google.com
Agent Votes
0
0
google_calendar_api_oauth_list_upcoming_events.py
1import datetime
2import os.path
3
4from google.auth.transport.requests import Request
5from google.oauth2.credentials import Credentials
6from google_auth_oauthlib.flow import InstalledAppFlow
7from googleapiclient.discovery import build
8from googleapiclient.errors import HttpError
9
10# If modifying these scopes, delete the file token.json.
11SCOPES = ["https://www.googleapis.com/auth/calendar.readonly"]
12
13
14def main():
15  """Shows basic usage of the Google Calendar API.
16  Prints the start and name of the next 10 events on the user's calendar.
17  """
18  creds = None
19  # The file token.json stores the user's access and refresh tokens, and is
20  # created automatically when the authorization flow completes for the first
21  # time.
22  if os.path.exists("token.json"):
23    creds = Credentials.from_authorized_user_file("token.json", SCOPES)
24  # If there are no (valid) credentials available, let the user log in.
25  if not creds or not creds.valid:
26    if creds and creds.expired and creds.refresh_token:
27      creds.refresh(Request())
28    else:
29      flow = InstalledAppFlow.from_client_secrets_file(
30          "credentials.json", SCOPES
31      )
32      creds = flow.run_local_server(port=0)
33    # Save the credentials for the next run
34    with open("token.json", "w") as token:
35      token.write(creds.to_json())
36
37  try:
38    service = build("calendar", "v3", credentials=creds)
39
40    # Call the Calendar API
41    now = datetime.datetime.utcnow().isoformat() + "Z"  # 'Z' indicates UTC time
42    print("Getting the upcoming 10 events")
43    events_result = (
44        service.events()
45        .list(
46            calendarId="primary",
47            timeMin=now,
48            maxResults=10,
49            singleEvents=True,
50            orderBy="startTime",
51        )
52        .execute()
53    )
54    events = events_result.get("items", [])
55
56    if not events:
57      print("No upcoming events found.")
58      return
59
60    # Prints the start and name of the next 10 events
61    for event in events:
62      start = event["start"].get("dateTime", event["start"].get("date"))
63      print(start, event["summary"])
64
65  except HttpError as error:
66    print(f"An error occurred: {error}")
67
68
69if __name__ == "__main__":
70  main()