Create Calendar Events From SharePoint Using MS Graph 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 creates events of the user in office 365 calendar
  • Method: POST
Endpoint
 
https://graph.microsoft.com/v1.0/users/[email protected]/events
 
Request Body
 
JSON with minimal parameters,
  1. var data = {  
  2.   "subject""My dummy event from graph",  
  3.   "start": {  
  4.     "dateTime""2019-07-05T18:05:23.218Z",  
  5.     "timeZone""UTC"  
  6.   },  
  7.   "end": {  
  8.     "dateTime""2019-07-12T18:05:23.218Z",  
  9.     "timeZone""UTC"  
  10.   }  
  11. }  
Tested in the Graph Explorer, it returns the JSON data like below.
 
Create Calendar Events From SharePoint Using MS Graph API
 
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
  1. <script type="text/javascript">  
  2.     var token;  
  3.     $(document).ready(function() {  
  4.         requestToken();  
  5.     });  
  6.     function requestToken() {  
  7.         $.ajax({  
  8.             "async"true,  
  9.             "crossDomain"true,  
  10.             "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    
  11.             "method""POST",  
  12.             "headers": {  
  13.                 "content-type""application/x-www-form-urlencoded"  
  14.             },  
  15.             "data": {  
  16.                 "grant_type""client_credentials",  
  17.                 "client_id ""8baf0301-27df-44b1-b4fe-7911b9a918de"//Provide your app id    
  18.                 "client_secret""tZ76oVPN039WlWPoAp+1aICq66vs7oUtE4lhDQYwxGY="//Provide your secret    
  19.                 "scope ""https://graph.microsoft.com/.default"  
  20.             },  
  21.             success: function(response) {  
  22.                 console.log(response);  
  23.                 token = response.access_token;  
  24.                 //     console.log(token);  
  25.                 RetrieveCalendarEvents();  
  26.             },  
  27.             error: function(error) {  
  28.                 console.log(JSON.stringify(error));  
  29.             }  
  30.         })  
  31.     }  
  32. </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
  1. <body>      
  2. <div class="container">      
  3. <div class="form-group">      
  4.     <label for="txtstartdate">StartDate:</label>      
  5.     <input type="text" class="form-control" id="txtstartdate" required>      
  6.   </div>      
  7.   <div class="form-group">      
  8.     <label for="txtenddate">EndDate:</label>      
  9.     <input type="text" class="form-control" id="txtenddate" required>      
  10.   </div>      
  11.    <div class="form-group">      
  12.     <label for="txtsubject">Subject:</label>      
  13.     <textarea class="form-control" id="txtsubject" rows="7" required></textarea>      
  14.   </div>      
  15.    <div class="form-group">      
  16.     <label for="txtmessage">Body:</label>      
  17.     <textarea class="form-control" id="txtbody" rows="7" required></textarea>      
  18.   </div>      
  19.   <button type="button" onclick="CreateCalendarEvents();" class="btn btn-default">Add Events</button>      
  20.   </div>     
  21. </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,
  1. <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>  
  2. <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>  
  3. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">  
  4. <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
  1. <script>  
  2.     $( function() {  
  3.     $("#txtstartdate, #txtenddate").datepicker();  
  4.   });  
  5. </script>  
Now dynamically pass the dynamic values into your JSON object and trigger the ” POST ” event. 
  1. function CreateCalendarEvents() {  
  2.   
  3.      var sdate = new Date($('#txtstartdate').val().toISOString())  
  4.      var edate = new Date($('#txtenddate').val().toISOString())  
  5.   
  6.      var subject = $('#txtsubject').val()  
  7.      var body = $('#txtbody').val()  
  8.   
  9.      var data = { "subject": subject, "start": { "dateTime": sdate , "timeZone""UTC"  
  10.     }, "end": { "dateTime": edate, "timeZone""UTC" }, body: {content: body}}  
  11.   
  12.         $.ajax({  
  13.             method: 'POST',  
  14.             url: "https://graph.microsoft.com/v1.0/users/[email protected]/events",  
  15.             headers: {  
  16.                 'Authorization''Bearer ' + token,  
  17.                 'Content-Type''application/json'  
  18.             },  
  19.             data: JSON.stringify(data),  
  20.             success: function(response) {  
  21.               alert("Event created")  
  22.             },  
  23.             error: function(error) {  
  24.             console.log("error", JSON.stringify(error))  
  25.             },  
  26.         })  
  27.       
  28.     }  
Now I call the entire HTML content into content editor webpart.
 
Let’s create one dummy event from SharePoint using MS Graph API
 
Create Calendar Events From SharePoint Using MS Graph API
 
Click “Add Events” button to create the event,
 
Create Calendar Events From SharePoint Using MS Graph API
 
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,
 
Create Calendar Events From SharePoint Using MS Graph API
 
Full Code
  1. <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>  
  2. <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>  
  3. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">  
  4. <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">    
  5. <script type="text/javascript">  
  6.     var token;  
  7.     $(document).ready(function() {  
  8.         requestToken();  
  9.     });  
  10.   
  11.     function requestToken() {  
  12.   
  13.         $.ajax({  
  14.             "async"true,  
  15.             "crossDomain"true,  
  16.             "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    
  17.             "method""POST",  
  18.             "headers": {  
  19.                 "content-type""application/x-www-form-urlencoded"  
  20.             },  
  21.             "data": {  
  22.                 "grant_type""client_credentials",  
  23.                 "client_id ""8baf0301-27df-44b1-b4fe-7911b9a918de"//Provide your app id    
  24.                 "client_secret""tZ76oVPN039WlWPoAp+1aICq66vs7oUtE4lhDQYwxGY="//Provide your secret    
  25.                 "scope ""https://graph.microsoft.com/.default"  
  26.             },  
  27.             success: function(response) {  
  28.                 console.log(response);  
  29.                 token = response.access_token;  
  30.                 //     console.log(token);  
  31.            //     RetrieveCalendarEvents();  
  32.             },  
  33.             error: function(error) {  
  34.                 console.log(JSON.stringify(error));  
  35.             }  
  36.         })  
  37.     }  
  38.   
  39.   
  40.     function CreateCalendarEvents() {  
  41.   
  42.      var sdate = new Date($('#txtstartdate').val())  
  43.      var edate = new Date($('#txtenddate').val())  
  44.   
  45.      var subject = $('#txtsubject').val()  
  46.      var body = $('#txtbody').val()  
  47.   
  48.      var data = { "subject": subject, "start": { "dateTime": sdate.toISOString(), "timeZone""UTC"  
  49.     }, "end": { "dateTime": edate.toISOString(), "timeZone""UTC" }, body: {content: body}}  
  50.   
  51.         $.ajax({  
  52.             method: 'POST',  
  53.             url: "https://graph.microsoft.com/v1.0/users/[email protected]/events",  
  54.             headers: {  
  55.                 'Authorization''Bearer ' + token,  
  56.                 'Content-Type''application/json'  
  57.             },  
  58.             data: JSON.stringify(data),  
  59.             success: function(response) {  
  60.               alert("Event Created")  
  61.             },  
  62.             error: function(error) {  
  63.             console.log("error", JSON.stringify(error))  
  64.             },  
  65.         })  
  66.       
  67.     }  
  68.   
  69. </script>  
  70.   
  71. <body>  
  72.     <div class="container">  
  73.         <div class="form-group">  
  74.             <label for="txtstartdate">StartDate:</label>  
  75.             <input type="text" class="form-control" id="txtstartdate" required>  
  76.         </div>  
  77.         <div class="form-group">  
  78.             <label for="txtenddate">EndDate:</label>  
  79.             <input type="text" class="form-control" id="txtenddate" required>  
  80.         </div>  
  81.         <div class="form-group">  
  82.             <label for="txtsubject">Subject:</label>  
  83.             <textarea class="form-control" id="txtsubject" rows="7" required></textarea>  
  84.         </div>  
  85.         <div class="form-group">  
  86.             <label for="txtmessage">Body:</label>  
  87.             <textarea class="form-control" id="txtbody" rows="7" required></textarea>  
  88.         </div>  
  89.         <button type="button" onclick="CreateCalendarEvents();" class="btn btn-default">Add Events</button>  
  90.     </div>  
  91.     <script>  
  92.         $( function() {  
  93.     $("#txtstartdate, #txtenddate").datepicker();  
  94.   } );  
  95.     </script>  
  96. </body>  
Happy Coding !......