Create calendar events from SharePoint using MSGraph API

In my previous article. I have written about how to authenticate your web application with Microsoft graph using oauth and consume the API

Now let’s see how to create a calendar event form your SharePoint site via custom HTML form.

Create Events To Calendar:

  • EndPoint – https://graph.microsoft.com/v1.0/users/{{userid}}/events
  • Usage – It create events of the user in office 365 calendar
  • Method: POST

Endpoint:

https://graph.microsoft.com/v1.0/users/vinodhvignesh@sharepointtechie.onmicrosoft.com/events

Request Body JSON with minimal parameters

var data = {
  "subject": "My dummy event from graph",
  "start": {
    "dateTime": "2019-07-05T18:05:23.218Z",
    "timeZone": "UTC"
  },
  "end": {
    "dateTime": "2019-07-12T18:05:23.218Z",
    "timeZone": "UTC"
  }
}

Tested in the Graph Explorer, it returns the JSON data like below.

So let’s see how to do this using JQuery AJAX- HTTP request

Step 1 – Fetch Access Token

AuthUrl: https://login.microsoftonline.com/{{tenant}}/oauth2/v2.0/token

Type: POST

<script type="text/javascript">
    var token;
    $(document).ready(function() {
        requestToken();
    });
    function requestToken() {
        $.ajax({
            "async": true,
            "crossDomain": true,
            "url": "https://howling-crypt-47129.herokuapp.com/https://login.microsoftonline.com/sharepointtechie.onmicrosoft.com/oauth2/v2.0/token", // Pass your tenant name instead of sharepointtechie  
            "method": "POST",
            "headers": {
                "content-type": "application/x-www-form-urlencoded"
            },
            "data": {
                "grant_type": "client_credentials",
                "client_id ": "8baf0301-27df-44b1-b4fe-7911b9a918de", //Provide your app id  
                "client_secret": "tZ76oVPN039WlWPoAp+1aICq66vs7oUtE4lhDQYwxGY=", //Provide your secret  
                "scope ": "https://graph.microsoft.com/.default"
            },
            success: function(response) {
                console.log(response);
                token = response.access_token;
                //     console.log(token);
                RetrieveCalendarEvents();
            },
            error: function(error) {
                console.log(JSON.stringify(error));
            }
        })
    }
</script>

 The successful response is below, with access token to authenticate the API directly from your webapplication

EndPoint:https://graph.microsoft.com/v1.0/users/{{userid}}/Events

Method: POST

HTML:

<body>  
<div class="container">  
<div class="form-group">  
    <label for="txtstartdate">StartDate:</label>  
    <input type="text" class="form-control" id="txtstartdate" required>  
  </div>  
  <div class="form-group">  
    <label for="txtenddate">EndDate:</label>  
    <input type="text" class="form-control" id="txtenddate" required>  
  </div>  
   <div class="form-group">  
    <label for="txtsubject">Subject:</label>  
    <textarea class="form-control" id="txtsubject" rows="7" required></textarea>  
  </div>  
   <div class="form-group">  
    <label for="txtmessage">Body:</label>  
    <textarea class="form-control" id="txtbody" rows="7" required></textarea>  
  </div>  
  <button type="button" onclick="CreateCalendarEvents();" class="btn btn-default">Add Events</button>  
  </div> 
</body> 

Let’s create a onclick event “CreateCalendarEvents()” to post the calendar events information like Startdate, Enddate,Subject and Body dynamically.

External References Used for DEMO purpose:

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

Initialize the datepicker control for two input elements startdate and endate

<script>
    $( function() {
    $("#txtstartdate, #txtenddate").datepicker();
  });
</script>

Now dynamically pass the dynamic values into your JSON object and trigger the ” POST ” event.

function CreateCalendarEvents() {

     var sdate = new Date($('#txtstartdate').val().toISOString())
     var edate = new Date($('#txtenddate').val().toISOString())

     var subject = $('#txtsubject').val()
     var body = $('#txtbody').val()

	 var data = { "subject": subject, "start": { "dateTime": sdate , "timeZone": "UTC"
	}, "end": { "dateTime": edate, "timeZone": "UTC" }, body: {content: body}}

        $.ajax({
            method: 'POST',
            url: "https://graph.microsoft.com/v1.0/users/vinodhvignesh@sharepointtechie.onmicrosoft.com/events",
            headers: {
                'Authorization': 'Bearer ' + token,
                'Content-Type': 'application/json'
            },
            data: JSON.stringify(data),
            success: function(response) {
              alert("Event created")
            },
            error: function(error) {
            console.log("error", JSON.stringify(error))
            },
        })
    
    }

Now i call the entire HTML content into content editor webpart

Let’s create one dummy event from SharePoint using MS Graph API

Click “Add Events” button to create the event

It successfully created the event into your outlook calendar. also some sample event created for testing

Take a look at it in my outlook calendar

Full Code:

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">


<script type="text/javascript">
	var token;
    $(document).ready(function() {
        requestToken();
    });

    function requestToken() {

        $.ajax({
            "async": true,
            "crossDomain": true,
            "url": "https://howling-crypt-47129.herokuapp.com/https://login.microsoftonline.com/sharepointtechie.onmicrosoft.com/oauth2/v2.0/token", // Pass your tenant name instead of sharepointtechie  
            "method": "POST",
            "headers": {
                "content-type": "application/x-www-form-urlencoded"
            },
            "data": {
                "grant_type": "client_credentials",
                "client_id ": "8baf0301-27df-44b1-b4fe-7911b9a918de", //Provide your app id  
                "client_secret": "tZ76oVPN039WlWPoAp+1aICq66vs7oUtE4lhDQYwxGY=", //Provide your secret  
                "scope ": "https://graph.microsoft.com/.default"
            },
            success: function(response) {
                console.log(response);
                token = response.access_token;
                //     console.log(token);
           //     RetrieveCalendarEvents();
            },
            error: function(error) {
                console.log(JSON.stringify(error));
            }
        })
    }


    function CreateCalendarEvents() {

     var sdate = new Date($('#txtstartdate').val())
     var edate = new Date($('#txtenddate').val())

   

     var subject = $('#txtsubject').val()
     var body = $('#txtbody').val()

	 var data = { "subject": subject, "start": { "dateTime": sdate.toISOString(), "timeZone": "UTC"
	}, "end": { "dateTime": edate.toISOString(), "timeZone": "UTC" }, body: {content: body}}

        $.ajax({
            method: 'POST',
            url: "https://graph.microsoft.com/v1.0/users/vinodhvignesh@sharepointtechie.onmicrosoft.com/events",
            headers: {
                'Authorization': 'Bearer ' + token,
                'Content-Type': 'application/json'
            },
            data: JSON.stringify(data),
            success: function(response) {
              alert("Event Created")
            },
            error: function(error) {
            console.log("error", JSON.stringify(error))
            },
        })
    
    }

</script>

<body>
	<div class="container">
		<div class="form-group">
			<label for="txtstartdate">StartDate:</label>
			<input type="text" class="form-control" id="txtstartdate" required>
		</div>
		<div class="form-group">
			<label for="txtenddate">EndDate:</label>
			<input type="text" class="form-control" id="txtenddate" required>
		</div>
		<div class="form-group">
			<label for="txtsubject">Subject:</label>
			<textarea class="form-control" id="txtsubject" rows="7" required></textarea>
		</div>
		<div class="form-group">
			<label for="txtmessage">Body:</label>
			<textarea class="form-control" id="txtbody" rows="7" required></textarea>
		</div>
		<button type="button" onclick="CreateCalendarEvents();" class="btn btn-default">Add Events</button>
	</div>
	<script>
		$( function() {
    $("#txtstartdate, #txtenddate").datepicker();
  } );
	</script>
</body>

Happy Sharepointing…..


Vinodh

Vinodh is a Microsoft MVP for SharePoint (Office Apps and Services) having 5+ years of experience in Microsoft Technologies. His interest and expertise includes SharePoint Online Development, PowerApps Development, Flows for SharePoint and PowerApps. Single Page Apps/Add ins for SharePoint using React, Angular. SharePoint Farm Management, 2, 3 and upto 6 tier SharePoint Farm Installation and Configuration. Awards : Microsoft Most Valuable Professional for SharePoint and Office 365 awarded for the year 2016, 2017 and 2018. C# Corner Most Valuable Professional for SharePoint and Office 365 awarded for the year 2016, 2017 and 2018. Technology Expertise : SharePoint Online, SharePoint 2013, SharePoint 2016 and SharePoint 2019 Preview. Intranets both Modern and Classic, SharePoint Frameworks Customisation, SharePoint Add-ins, SharePoint single page apps. Angular 5 with Bootstrap single page apps. Typescript, JQuery and Javascript. Micrsoft Flow and Powerapps. Utilised : Microsoft Graph API, SharePoint REST, SharePoint PnP JS. Out of Box : Consume Content search web parts for internet publishing sites using custom display templates. Having knowledge on SharePoint workflows and SharePoint Designer workflows. List customisation using JS Link, JSON Formatting. Having knowledge in Active directory management services. Create and configure service applications in SharePoint (MMS, UPSA, SSA). Configure Outgoing email settings using SMTP Services.

Add a Comment

Your email address will not be published. Required fields are marked *