How to schedule events with any calendar API

How to schedule events with any calendar API

7 min read
Tags:

If you’ve been reading our posts, you know how to schedule Calendar events using Ruby, Python, Node and Java.

But you may be wondering, can I use something else? Can I use R, Julia or Perl?

Well, the simple answer is yes, we absolutely can! Nylas provides Restful APIs, not only SDKs, so we can use any available programming language that is able to make API calls.

We’ll consider some code samples that are more proof of concepts instead of full-fledged applications. There are several ways to consume the Nylas APIs, and this blog post intends to show one way of doing that.

We’re going to learn how to schedule events using the Nylas API.

What are we going to talk about?

Getting a Calendar Id

Before we can move on, we need to have a Calendar Id, as the events need to be created on a calendar. Gladly, we can use a cURL command to get precisely that:

curl --request GET \
  --url 'https://api.nylas.com/calendars' \
  --header 'Authorization: Bearer <ACCESS_TOKEN> \
  --header 'Content-Type: application/json'

We need an ACCESS_TOKEN to authorize our application to access the Nylas APIs. You can get it from your dashboard if you have a Nylas account, otherwise, you can create an account for free.

This will return a list of calendars, and from there we can choose the Id of the calendar that we want to use:

Getting the calendar id

Scheduling an event using R

First, we need to have R installed and RStudio (The best IDE for R development). Once we have them both installed, we need to install the following packages:

httr → Tools for working with URLs and HTTP
dotevn → Load environment variables from .env files

To install them, the easiest way is to open up RStudio and select Tools → Install Packages. Then enter the package names separated by a comma or space:

Installing R packages

After clicking install, they will be ready to use.

Now, we need to create an .env file with the following information:

API_KEY="<ACCESS_TOKEN>"
CALENDAR_ID="<CALENDAR_ID>"

Then, we can create a file and call it CreateEvent.R with the following source code in order to schedule our event:

# Set the working directory
setwd("~/Blag/R_Codes")

# Call the needed libraries
library(httr)
library(dotenv)

# Load our .env file
load_dot_env(file = ".env")

#Define the body of our call
body = paste('{"title": "Learn R with Nylas",
         "when": {"start_time": 1672567200,
                  "end_time": 1672570800},
         "location": "Blag\'s Den",
         "calendar_id":"', Sys.getenv("CALENDAR_ID"),
         '", "participants": [
            {
              "email": "<EMAIL_ADDRESS>",
              "name": "Blag"
            }
          ]
        }');

# Set our API Key or Access Token
api_key <- Sys.getenv("API_KEY")

# Call the Event endpoint
result <- POST("https://api.nylas.com/events?notify_participants=true",
          body = body,
          add_headers(Authorization = paste("Bearer", api_key),
          `Content-Type` = "application/json", Accept = "application/json"))

# Print the response of the call
cat(content(result, 'text', encoding = "UTF-8"))

To run this code, we can either press the Source button on RStudio, press Command + Enter (Mac) or enter the following on the console window:

source("~/Blag/R_Codes/CreateEvent.R", echo=TRUE)

The console will return the result of calling the events endpoint:

Schedule a calendar event using R and the Nylas APIs

And we can check that we received the invitation for the event:

Event scheduled for learning R

Scheduling an event using Julia

To install Julia, we can use Brew:

$ brew install julia

Once installed, we need to add some packages, so on a terminal window type julia and then the following:

Add Julia packages

This will (if you don’t have them already) install the packages:

HTTP → Tools for working with URLs and HTTP
DotEnv → Load environment variables from .env files
JSON → Parsing and printing Json

Now, we need to create an .env file with the following information:

ACCESS_TOKEN=<ACCESS_TOKEN>
CALENDAR_ID=<CALENDAR_ID>

Then, we can create a file called CreateEvent.jl with the following code in order to schedule our event:

# Load packages
using DotEnv
using HTTP
using JSON

# Load .env file
cfg = DotEnv.config()

# Events endpoint
url = "https://api.nylas.com/events?notify_participants=true"

# Body of the call
payload = Dict("title" => "Learn Julia with Nylas",
                      "when" => Dict("start_time" => 1672567200, "end_time" => 1672570800),
                      "location" => "Blag\'s Den",
                      "calendar_id" => cfg["CALENDAR_ID"],
                      "participants" =>  [ Dict("email" => "<EMAIL_ADDRESS>",
                                                         "name" => "Blag")])

# Headers for authorization
headers = Dict(
    "Accept" => "application/json",
    "Content-Type"=> "application/json",
    "Authorization"=> "Bearer " * cfg["ACCESS_TOKEN"]
)

# Calling the endpoint
response = HTTP.post(url, headers, json(payload))
# Print the response of the call
print(response)

To run this code, we need to call the julia interpreter:

$ julia CreateEvent.jl
Response from Julia

And here’s the response from the call:

Schedule a calendar event using Julia and the Nylas APIs

And we can check that we receive the invitation for the event:

Invitation scheduled to learn Julia

Scheduling and event using Perl

If we’re using Linux or Mac, then Perl should be installed already, otherwise, here are the instructions. When it comes to Windows, here are the instructions.

Once installed, one important thing is to install CPANM (Package manager). While CPAN (Comprehensive Perl Archive Network) is historically the best, CPANM is easier to use. 

We can install CPANM by using Brew:

$ brew install cpanminus

Once installed, let’s install additional packages:

$ cpanm Mozilla::CA

$ cpanm Dotenv

Mozilla::CA will help us with SSL authentication, while Dotenv will help us working with .env files.

Now, we need to create an .env file with the following information:

ACCESS_TOKEN=<ACCESS_TOKEN>
CALENDAR_ID=<CALENDAR_ID>

Then, we can create a file called CreateEvent.pl with the following code in order to schedule our event:

#!/usr/bin/perl
# Pragmas to ensure code quality
use strict;
use warnings;
use diagnostics;
# Call packages
use HTTP::Request ();
use Encode qw(encode_utf8);
use JSON::MaybeXS qw(encode_json);
use LWP::UserAgent;
use Dotenv;

# Load .env file
my $env = Dotenv->parse('.env');

# Access .env file variables
my $access_token = $ { $env} { ACCESS_TOKEN };
my $calendar_id = $ { $env} { CALENDAR_ID };

# Create new User Agent to call API
my $user_agent = LWP::UserAgent->new();
# Define API endpoint
my $url = 'https://api.nylas.com/events?notify_participants=true';
# Body of the API call
my $data = {title => "Learn Perl with Nylas",
                   when => {start_time => 1672671600, end_time => 1672675200},
                   location => "Blag\'s Den",
                   calendar_id => $calendar_id,
                   participants =>  [{email => "atejada\@gmail.com",
                                             name => "Blag"}]};
# Encode data as JSON
my $encoded_data = encode_utf8(encode_json($data));
# Define API endpoint call
my $request = HTTP::Request->new(POST => $url);
# Pass headers
$request->header('Accept' => 'application/json');
$request->header('Authorization' => "Bearer $access_token");
# Pass body
$request->content($encoded_data);

# Use User Agent to make API endpoint call
my $response = $user_agent->request($request);
# If succesful, then print result
if ($response->is_success) {
    my $message = $response->decoded_content;
    print "Received reply: $message";
}
# Otherwise, show the error message
else {
    print "HTTP POST error code: ", $response->code, "n";
    print "HTTP POST error message: ", $response->message, "n";
}

And here’s the response from the call:

Schedule a calendar event using Perl and the Nylas APIs

And we can check that we receive the invitation for the event:

Invitation scheduled for learning Perl

What’s next?

We learned how easy is to schedule events using the Nylas API.

Don’t miss the action, follow our LiveStream Coding with Nylas:

You can check our documentation on Events. Or you can read our post How to Send an Email in Any Language Using the Nylas APIs.

Related resources

How to Solve Webhook Integration Challenges with PubSub Notification Channel

Key Takeaways This article addresses the challenges of webhook integration and introduces the PubSub Notification…

How to Send Emails Using an API

Key Takeaways This post will provide a complete walkthrough for integrating an email API focused…

How to build a CRM in 3 sprints with Nylas

What is a CRM? CRM stands for Customer Relationship Management, and it’s basically a way…