- Products
- Solutions Use casesBy industry
- Developers
- Resources Connect
- Pricing
In this blog post, we integrate Google Calendar API with Python. We’ve previously explored and discussed the Google Calendar API, and this blog post focuses on managing Google Calendar over API using the Python language. We will be using the Nylas APIs to connect to the Google Calendar API, let’s chat about Nylas before we dive in.
The Nylas APIs allow developers to manage all communication data (Calendar, Email, Contact) using a single API that seamlessly integrates with all providers (i.e. Outlook, Yahoo, Google, iCloud). We recently discussed build vs. buy decisions and how tricky some integrations like IMAP can be.
Let’s consider reasons to build with Python to integrate with Google Calendar API
We will integrate the Nylas Python SDK with the Google Calendar API. The benefit of using an SDK over Restful API calls is that we can use Python functions to retrieve data from a Google Calendar to make calls to the Nylas API.
Let’s dive in!
For this blog post, we reference the Nylas Quickstart Guides with downloadable code that you can run locally on your machine or using Github Codespaces. Let’s go through the steps to get started:
Before you continue, ensure the download code contains a pre-filled .env file with the Nylas credentials.
⚠️Note: Ensure the environment variables are not shared or pushed to a remote git repository.
Ensure you are using Python 3.7 or later. We can check this by running the following:
python3 --version
To install the Nylas Python SDK, included in the Quick Start Guide, run the following command:pip install nylas
Let’s set up the Nylas Python SDK using the environment variables we received:
nylas = APIClient( os.environ.get("NYLAS_CLIENT_ID"), os.environ.get("NYLAS_CLIENT_SECRET"), api_server = os.environ.get("NYLAS_API_SERVER") or "https://api.nylas.com" )
For the API Server, check that you are following the URL for your region. We can double check our docs on data residency.
The environment variables can be found in the Nylas Dashboard under App Settings:
We have initialized the Nylas SDK and are ready to authenticate users.
For connecting a user to retrieve their calendar data, we will use authentication provided by Nylas. For the Quick Start Guide, we provide a sandbox environment with credentials to connect user accounts, so you are ready to go!
Consider our guides on a Google Project or Azure App if you are setting up a new project. The guides show you how to setup up authentication on your own and add your credentials to the Nylas dashboard.
The Quick Start Guide requests an email to authenticate and starts the Nylas authentication flow with the following code:
@flask_app.route("/nylas/generate-auth-url", methods=["POST"]) def build_auth_url(): request_body = request.get_json() # SDK method generates a Nylas Hosted Authentication URL auth_url = nylas.authentication_url( (CLIENT_URI or "") + request_body["success_url"], login_hint=request_body["email_address"], scopes=['calendar'], state=None, ) return auth_url
Once the user is redirected from an application like Google Calendar, we are given an authorization code to exchange for an access token. The access token is what we can use to make requests on the user’s behalf:
@flask_app.route("/nylas/exchange-mailbox-token", methods=["POST"]) def exchange_code_for_token(): request_body = request.get_json() # SDK method exchanges authorization code for an access token access_token_obj = nylas.send_authorization(request_body["token"]) # process the result and send to client however you want access_token = access_token_obj['access_token'] email_address = access_token_obj['email_address'] print('Access Token was generated for: ' + email_address) # Store user credentials in in-memory database user = db.create_or_update_user(email_address, { 'access_token': access_token, 'email_address': email_address }) return { 'id': user['id'], 'emailAddress': user['email_address'] }
Here is an example of the hosted authentication flow that you can try out from the Nylas Quickstart:
Let’s look at how we can fetch events for the Google Calendar API in Python. Here is the code for fetching calendar events:
@flask_app.route('/nylas/read-events', methods=['GET']) @is_authenticated def read_events(): # pass in the criteria for searching for calendar events calendar_id = request.args.get('calendarId') starts_after = request.args.get('startsAfter') ends_before = request.args.get('endsBefore') limit = request.args.get('limit') res = nylas.events.where( calendar_id=calendar_id, starts_after=starts_after, ends_before=ends_before, limit=int(limit) ).all() # enforce_read_only=False is used to return the full event objects res_json = [item.as_json(enforce_read_only=False) for item in res] return res_json
We can retrieve calendar events from the Google Calendar API in Python using Nylas.
Let’s look at how to create new events for the Google Calendar API in Python. Here is the code for creating calendar events:
@flask_app.route('/nylas/create-events', methods=['POST']) @is_authenticated def create_events(): request_body = request.get_json() calendar_id = request_body['calendarId'] title = request_body['title'] description = request_body['description'] start_time = request_body['startTime'] end_time = request_body['endTime'] participants = request_body['participants'] if not calendar_id or not title or not start_time or not end_time: return 'Missing required fields: calendarId, title, starTime or endTime', 400 event = nylas.events.create() event.title = title event.description = description event.when = { 'start_time': start_time, 'end_time': end_time, } event.calendar_id = calendar_id if participants: event.participants = [{"email": email} for email in participants.split(", ")] event.save(notify_participants=True) return event.as_json(enforce_read_only=False)
We can retrieve calendar events from the Google Calendar API in Python using Nylas.
Let’s look at how we can modify events for the Google Calendar API in Python. This will be very similar to creating events, just that we need to provide an eventId for the event we like to update.
Here is the code for modifying calendar events:
@flask_app.route('/nylas/update-events', methods=['POST']) @is_authenticated def create_events(): request_body = request.get_json() event_id = request_body['eventId'] calendar_id = request_body['calendarId'] title = request_body['title'] description = request_body['description'] start_time = request_body['startTime'] end_time = request_body['endTime'] participants = request_body['participants'] if not calendar_id or not event_id or not title or not start_time or not end_time: return 'Missing required fields: eventId, calendarId, title, starTime or endTime', 400 event = nylas.events.get(event_id) if event.read_only: return 'You can only modify events that are not ready only for the user' # modify event parameters event.title = title event.description = description event.when = { 'start_time': start_time, 'end_time': end_time, } event.calendar_id = calendar_id if participants: event.participants = [{"email": email} for email in participants.split(", ")] event.save() return event.as_json(enforce_read_only=False)
Now, we can modify calendar events from the Google Calendar API in Python using Nylas.
Let’s look at how we can delete calendar events using Nylas:
@flask_app.route('/nylas/delete-events', methods=['POST']) @is_authenticated def create_events(): request_body = request.get_json() event_id = request_body['eventId'] if not event_id: return 'Missing required fields: eventId', 400 nylas.events.delete(event_id, notify_participants='true') data = {"status": "success"} return data, 200
Now, we can modify and delete calendar events from the Google Calendar API in Python using Nylas.
You can sign up for Nylas for free and start building! Continue building with Nylas by exploring quickstart guides or visiting our developer documentation.
Ram loves teaching, building and exploring technologies. He is passionate about empowering developers to ship amazing products to market as fast as possible ????. Ram is excited to share knowledge and help others. He’s a Relaxed Tomato ????.