Get calendar events in SharePoint using Graph API

Graph API Introduction

Microsoft Graph API (Application Programming Interface) is the involvement of Office 365 Unified API into a single stop for a cloud solution by exposing multiple Microsoft cloud service APIs through a single REST (Representational State Transfer) API endpoint.

With the Office Graph, the user has created a web that consists of content and communication.  Each piece of content is a node.  Each person is a node.  Each form of communication is a node.  Office Graph connects these nodes together through specific APIs.  Each one has its own API.  Office Graph creates a small web for each user, whereas, Microsoft Graph API creates a web not only for one user but interlinks related users across an entire organization resulting in a large web of collaboration and communication.

Here is an image that shows how we can use Office Graph to connect and surface data among different areas of the Office 365 and Azure stacks.

The larger the web, the slower the time to access and find data.  Microsoft Graph API retained the inherent machine learning capabilities as one of the responses to this issue.  By collecting and analyzing, the machine learning algorithm allows Microsoft Graph API to learn the users working relationships and brings to the forefront the most frequented services not only for each individual user but as an organization as a whole by connecting each individual with collaborators and teams.

The single and greatest response to cloud data congestion is that Microsoft Graph API was evolved further so that multiple API exposures from Microsoft Cloud services are handled through a single REST API endpoint.  In other words, there is one endpoint to rule them all!

Today’s Solution

Today we are going to perform business Oriented solution which will be going to help each and every logged in users a handy Benefit to know the meeting schedules from the outlook calendar. It will help you to get your availability for task and meeting planning.

We can enhance this solution to Get the free/busy availability information for a collection of users, distributions lists, or resources, for a specified time.

Permissions

One of the following permissions is required to call this API. A user must have enough permission for getting outlook data. This is the List of Permissions one of them is necessary to perform this API Operation.

Permission type Permissions (from least to most privileged)
Delegated (work or school account) Calendar.Read, Calendar.ReadWrite
Delegated (personal Microsoft account) Not supported.
Application Calendar.Read, Calendar.ReadWrite

HTTP Request

POST /me/calendar/getSchedule 
POST /users/{id|userPrincipalName}/calendar/getSchedule

Request Headers

Name Type Description
Authorization string Bearer {token}. Required.
Content-Type string Nature of the data in the body of an entity, which is application/json. Required.
Prefer: outlook.timezone string Use this to specify the time zone for start and end times in the response. If not specified, those time values are returned in UTC. Optional.

Request body

In the request body, provide a JSON object with the following parameters.

Property Type Description
availabilityViewInterval String Represents the duration of a time slot in an availabilityView in the response. The default is 30 minutes, the minimum is 6, maximum is 1440. Optional.
endTime dateTimeTimeZone The date, time, and time zone that the period ends.
schedules String collection A collection of SMTP addresses of users, distribution lists, or resources to get availability information for.
startTime dateTimeTimeZone The date, time, and time zone that the period starts.

Response

If successful, this method returns a 200 OK response code and a collection of schedule information objects for each object in the schedules parameter.

Application

find meeting times applies certain business logic to suggest meeting times and locations, such as:

  • Optional or mandatory attendance of each entity
  • The nature of the requested activity for the time of the day
  • The minimum attendance required for a quorum for a meeting

It is appropriate for scenarios that depend on streamlining appointment booking.

GetSchedule: Simply returns the free/busy status of existing events in each of the requested calendars for a given time period and assumes the remaining time in that time period to be free. You would then apply further business logic to make use of this data to complete your scenario.

Prerequisites

Azure Application with required permissions and, Application ID of the Application which we have created into the Azure Active directory.

Create Application into Azure

  1. Go to https://portal.azure.com and log in with your O365 admin credentials
  2. Click on “Azure Active Directory” option from the left navigation
  3. Then click on “App registrations” option
  4. Click on “Add” button to register your app and fill in the required information and then click on “Create” button
  5. Please copy “Application ID” value. Here “Application ID = Client ID” i.e. Client ID value asked in graphapi.js file
  6. Edit the manifest and activate implicit OAuth
    1. Click on the new registration you have created
    2. Now Click on the “Menifest” button
    3. Now Click on “Edit” button
    4. Now change “oauth2AllowImplicitFlow” to true
    5. Click on Save button to save the manifest file settings
  7. Settings App Access Permission
    (Please note that these settings are depending on what type of graph query you have used in your app. E.g. Query regarding the user, email, list items etc.…)
    Following is the example of permission I have given to read user profile of the user.

    1. Click on the new registration you have created
    2. Click on “API Accessà Required Permissions”
    3. Click on default permission settings you want give one of permission as mentioned above into the Permissions Portion.
    4. Select permission as your requirement
    5. Click “Save” button
    6. Click on “Grant Permission” button
    7. Click on “Yes”

Now we have the Azure application registered with required permissions.

Create an HTML File with Graph API Operation

Let’s create the Solution based on the Graph API services and the build a proper solution to get the Logged-in user’s schedule as per the Events or Items created into the Outlook calendar.

Step 1: Create the HTML design with two date Inputs and add a button for the pass that dates to the code for getting the scope to get Data from the Outlook calendar.

Step 2: Create the Script and implement the Graph API into the Script. I have added the HTML file which has HTML content and Script both. Please find below Github URL.

$(function(){

$('#btndate').click(function(){
if(accessToken && accessToken != "" && ($( "#fromDatepicker" ).val() != "" && $( "#fromDatepicker" ).val() != "")){
getSchedular();
} 
});

$( "#fromDatepicker" ).datepicker();
$( "#toDatepicker" ).datepicker();

console.log('Loading'); 

var accessToken = "";

var configOptions = {
clientId: "bf4aaa94-f2a8-4009-808a-890ceea5dd6d", //Required clientId to get accessToken
postLogoutRedirectUri: window.location.origin,
redirectURI: window.location.href, // Your page link
//cacheLocation: "localStorage", //Optional to save data in localStorage by defualt it store in session storage
}

window.authContext = new AuthenticationContext(configOptions);


if(authContext.isCallback(window.location.hash))
{
authContext.handleWindowCallback(); //Using this we can get user from getCachedUser() after login
}

var user = authContext.getCachedUser(); 
if(user == null){
authContext.login(); //Login if user not found in getCachedUser
}
else
{
//setTimeout(function(){ getToken(); }, 1000);
//setTimeout(function(){ getUser(); }, 3000);
getToken(); 

}

function getToken(){ //get accessToken 
authContext.acquireToken("https://graph.microsoft.com",function(error, token){
console.log("Error =" +error);
console.log("Token =" +token);
accessToken = token;
if(accessToken && accessToken != "")
{
//getSchedular(); 
}
})
}

function getSchedular(){ // get data based on passed url
var schedular = { 
"Schedules": [_spPageContextInfo.userEmail],
"StartTime": {
"dateTime": new Date($( "#fromDatepicker" ).val()).format('yyyy/MM/ddTh:mm:ss'),
"timeZone": "India Standard Time"
},
"EndTime": {
"dateTime": new Date($( "#toDatepicker" ).val()).format('yyyy/MM/ddTh:mm:ss'),
"timeZone": "India Standard Time"
},
"availabilityViewInterval": "15"
}

$.ajax({
url: "https://graph.microsoft.com/beta/me/calendar/getschedule", 
type: 'POST', 
headers: {
'Content-Type': 'application/json',
'Prefer': 'outlook.timezone="Indian Standard Time"',
"Authorization": "Bearer " + accessToken
},
data:JSON.stringify(schedular),
async:false,
success: function(data) {
$('#scheduleData tbody').empty();
allData = data.value;
$.each(allData,function(e,item){
$.each(item.scheduleItems,function(i,itm){
$('#scheduleData tbody').append('<tr><td>'+new Date(itm.start.dateTime).format('dd/MM/yyyy, h:mm:ss')+'</td>'+
'<td>'+new Date(itm.end.dateTime).format('dd/MM/yyyy, h:mm:ss')+'</td>'+
'<td>'+(itm.subject?itm.subject:"")+'</td>'+
'<td>'+(itm.status?itm.status:"")+'</td>'+
'<td>'+(itm.location?itm.location:"")+'</td></tr>');
}) 
}) 
},
error: function(error) 
{ 
alert("Error" + error);
}
});//ajax
}//get user
})

Step 3: You should make some changes into the Script as per your Applications and the Site collection of yours.
Apply your Configurations at given highlighted places.

  1. Apply your Application ID which you can get by the Application you have generated into the Azure.
  2. Apply your Graph API URL as per your requirement and also provide your Time zone.

Working Solution

Here is the Working Solution which shows the Logged-in Users Free busy Schedule as per the Events created into the Office 365 Outlook calendar.

Step 1: For this Solution, we must have events or meetings created into the Outlook calendar, Otherwise, it won’t show us any data.

Below given Image is the Outlook calendars Image of my Office 365 outlook calendar.

And this is my outlook calendars Picture which has the Original events of Office 365 Outlook Calendar.

If you want to download the source code follow the Github URL:

https://github.com/mindlabco/FreeBusySchedule

 

Important Note: As you aware, APIs under the /beta version in Microsoft Graph are in preview and are subject to change. Use of these APIs in production applications is not supported.

Paras Dodhia

Leave a Reply