Calendar - Nylas Python API

How to manage calendar events with the Nylas Python SDK

8 min read

The Nylas Calendar API can power your application with a secure, reliable connection to your users’ calendars. You can use the Nylas Calendar API to sync historic and future events into your application and perform full CRUD operations on calendar items.

To make things even easier for Python developers, we offer the Nylas Python SDK. Today we’re going to review how to manage calendar events with Python using the SDK.

Is your system ready?

If you already have the Nylas Python SDK installed and your environment is configured, then you’re ready to follow along with this post.

Otherwise, I recommend that you read the post How to Send Emails with the Nylas Python SDK where the setup and configuration are clearly explained.

Reading calendars

Now we get to write some code! For my code editor, I’m going to use Geany, however, you can use the IDE of your choice.

We’re going to call this file ReadCalendars.py:

# Load your env variables
from dotenv import load_dotenv
load_dotenv()

# Import your dependencies
import os
from nylas import APIClient

# Initialize your Nylas API client
nylas = APIClient(
    os.environ.get("CLIENT_ID"),
    os.environ.get("CLIENT_SECRET"),
    os.environ.get("ACCESS_TOKEN"),
)

# Access and print all calendars information
calendars = nylas.calendars.all()
for calendar in calendars:
	print("Id: {} | Name: {} | Description: {}".format(
          calendar.id, calendar.name, calendar.description))

We can run this script from the terminal by using:

$ python3 ReadCalendars.py

Which will give us output that looks like this:

Read Calendars

As we can see, we’re going to get back a list of all the available calendars for our account.

Note that each of the calendars returned has an id. You’ll need at least one of those ids in the following steps.

Reading events

One advantage of being able to read a Calendar is of course being able to read events, so that’s what we’re going to do now. We’re going to choose a Calendar and read its related events.

For that, we’re going to create the new file below called ReadEvents.py. Note that in this script, we’re going to need to supply one of the Calendar ids from the previous step:

# Load your env variables
from dotenv import load_dotenv
load_dotenv()

# Import your dependencies
import os
import datetime
from datetime import date
from nylas import APIClient

# Initialize your Nylas API client
nylas = APIClient(
  os.environ.get("CLIENT_ID"),
  os.environ.get("CLIENT_SECRET"),
  os.environ.get("ACCESS_TOKEN"),
)

# Get today’s date
today = date.today()
# Today’s date at 12:00:00 am
AFTER = int(datetime.datetime(today.year, today.month, today.day, 0, 0, 0).strftime('%s'))
# Today’s date at 11:59:59 pm
BEFORE = int(datetime.datetime(today.year, today.month,today.day, 23, 59, 59).strftime('%s'))

# Access and print all events information
events = nylas.events.where(calendar_id="<your_calendar_id>",  starts_after=AFTER, ends_before=BEFORE)

for event in events:
# This is a event with an start and end date
  if "start_time" in event.when:
      print("Title: {} | Start: {} | End: {} | Participants: {}\n".format(
		event.title, 
		datetime.datetime.fromtimestamp(event.when['start_time']).strftime('%Y-%m-%d %H:%M:%S'), 
		datetime.datetime.fromtimestamp(event.when['end_time']).strftime('%Y-%m-%d %H:%M:%S'), 
		event.participants
	  ))
# This an all-day event  
  else:
      print("Title: {} | Date: {} | Participants: {}\n".format(
		event.title, 
		event.when["date"],
		event.participants
	  ))

We can run this script from the terminal by using:

$ python3 ReadEvents.py

Which will give us output that looks like this:

Read Events

Reading events is important, but maybe there’s something more important: creating events!

Creating events

Let’s try creating a new event using the Nylas Calendar API. We’re going to need to plug the following into our new script:

  1. An email address to send the invitation to
  2. The Calendar id for the calendar that sends the invitation

We’re going to name this file CreateEvent.py:

# Load your env variables
from dotenv import load_dotenv
load_dotenv()

# Import your dependencies
import os
import datetime
from datetime import date
from nylas import APIClient

# Initialize your Nylas API client
nylas = APIClient(
    os.environ.get("CLIENT_ID"),
    os.environ.get("CLIENT_SECRET"),
    os.environ.get("ACCESS_TOKEN"),
)

# Get today’s date
today = date.today()
# Today’s date at 12:00:00 am
START_TIME = int(datetime.datetime(today.year, today.month, today.day, 13, 10, 0).strftime('%s'))
# Today’s date at 11:59:59 pm
END_TIME = int(datetime.datetime(today.year, today.month, today.day, 14, 0, 0).strftime('%s'))

# Create event draft
event = nylas.events.create()

# Define event elements
event.title = "Let's learn some Nylas Python SDK!"
event.location = "Blag's Den!"
event.when = {"start_time": START_TIME, "end_time": END_TIME}
event.participants = [{"name": "Blag", 'email': '<your_email>'}]
event.calendar_id = "<your_calendar_id>"

# We would like to notify participants
event.save(notify_participants=True)
if event.id:
	print("Event created successfully")
else:
	print("There was an error creating the event")

We can run this script from the terminal by using:

$ python3 CreateEvent.py

We’ll get an email notification:

Event invitation

And the event will appear on our calendar as well:

Event in Calendar

We have reviewed how to create an event, which turns out to be fairly simple.

Updating events

Plans change! Sometimes we need to delay a meeting, or we realize that we forgot to add something to an invite. There are any number of reasons we might need to update an invitation.

To modify or update a calendar event, we need to have the event id. If we modify our ReadEvents.py script slightly, we can easily get that (again, be sure to use the Calendar id we got in a previous step in this script):

# Load your env variables
from dotenv import load_dotenv
load_dotenv()

# Import your dependencies
import os
import datetime
from datetime import date
from nylas import APIClient

# Initialize your Nylas API client
nylas = APIClient(
    os.environ.get("CLIENT_ID"),
    os.environ.get("CLIENT_SECRET"),
    os.environ.get("ACCESS_TOKEN"),
)

# Get today’s date
today = date.today()
# Today’s date at 12:00:00 am
AFTER = int(datetime.datetime(today.year, today.month,
            today.day, 0, 0, 0).strftime('%s'))
# Today’s date at 11:59:59 pm
BEFORE = int(datetime.datetime(today.year, today.month,
             today.day, 23, 59, 59).strftime('%s'))

# Access and print all events information
events = nylas.events.where(
    calendar_id="<your_calendar_id>", starts_after=AFTER, ends_before=BEFORE)

for event in events:
    # This is a event with an start and end date
    if "start_time" in event.when:
        print("Id: {}, Title: {} | Start: {} | End: {} | Participants: {}\n".format(
            event.id,
            event.title,
            datetime.datetime.fromtimestamp(
                event.when['start_time']).strftime('%Y-%m-%d %H:%M:%S'),
            datetime.datetime.fromtimestamp(
                event.when['end_time']).strftime('%Y-%m-%d %H:%M:%S'),
            event.participants
        ))
    # This an all-day event
    else:
        print("Id: {}, Title: {} | Date: {} | Participants: {}\n".format(
            event.id,
            event.title,
            event.when["date"],
            event.participants
        ))

We can run this script from the terminal by using:

$ python3 ReadEvents.py

Which will give us output that looks like this:

Read events with Id

From the output, we need to grab one of the event IDs. With that, we can create a new script and call it UpdateEvent.py:

# Load your env variables
from dotenv import load_dotenv
load_dotenv()

# Import your dependencies
import os
import datetime
from datetime import date
from nylas import APIClient

# Initialize your Nylas API client
nylas = APIClient(
    os.environ.get("CLIENT_ID"),
    os.environ.get("CLIENT_SECRET"),
    os.environ.get("ACCESS_TOKEN"),
)

# Get today’s date
today = date.today()

# Get the event information
event = nylas.events.get('<your_event_id>')

START_TIME = int(datetime.datetime(today.year, today.month, today.day, 12, 0, 0).strftime('%s'))
END_TIME = int(datetime.datetime(today.year, today.month, today.day, 14, 0, 0).strftime('%s'))
event.when = {"start_time": START_TIME, "end_time": END_TIME}

# Update the event information
event.save(notify_participants=True)
if event.id:
	print("Event updated successfully")
else:
	print("There was an error updating the event")

You will receive an email notifying you of the change:

Updated invitation

And the event in the calendar is going to be updated as well:

Updated invitation on Calendar

As we’ve seen here, updating an event is as easy as creating one. The Nylas SDK is flexible enough to make working with events simple and straightforward.

Deleting events

Just for the sake of completion and taking advantage of the fact that we have the event id, let’s create a quick script to delete events. We’re going to need the event id of the event that we want to delete.

We’re going to call this file DeleteEvent.py:

# Load your env variables
from dotenv import load_dotenv
load_dotenv()

# Import your dependencies
import os
import datetime
from nylas import APIClient

# Initialize your Nylas API client
nylas = APIClient(
    os.environ.get("CLIENT_ID"),
    os.environ.get("CLIENT_SECRET"),
    os.environ.get("ACCESS_TOKEN"),
)

# Delete the event and let participants know
nylas.events.delete('<event_id>', notify_participants=True)
# Look for the event
events = nylas.events.where(event_id='<event_id>')

# Check if event was deleted or not
try:
    _id = events.id	
    print("There was a problem deleting the event")
except:
    print("Even deleted successfully")

We will get an email notification and the event will be removed from our calendar:

Cancelled event

And that’s it! As you can see, by using the Nylas Python SDK, sending emails becomes an easy task. If you want to learn more, visit our Documentation Page.

Join our technical demo to see the Nylas Platform in action

Related resources

How to create an appointment scheduler in your React app

Learn how to create an appointment scheduler in your React app using Nylas Scheduler. Streamline bookings and UX with step-by-step guidance.

Beyond APIs: Designing elegant, smart Web Components

Dive into the world of smart Web Components for advanced API integration solutions. Design elegant, customizable elements to elevate user experiences.

How to integrate a React calendar component to streamline scheduling

Elevate your app’s scheduling with a React calendar component and seamlessly integrate with Nylas for efficient calendar management.