Search code examples
python-2.7restexchangewebservicesoffice365api

Creating multiple events in office365 rest api


I have below code which posts one calendar event to the events on office 365 REST API. I need to enter about 100 events to my calendar. Is there any way to place multiple events in the json data or should I use for loop?

import urllib2
import getpass
import os
import json
import sys
import base64


# Set the request parameters
url = 'https://outlook.office365.com/api/v1.0/me/events?$Select=Start,End'
user = '[email protected]'

pwd = getpass.getpass('Please enter your AD password: ')


# Create JSON payload
data = {
  "Subject": "My Subject",
  "Body": {
    "ContentType": "HTML",
    "Content": ""
  },
  "Start": "2015-08-11T07:00:00-05:00",
  "StartTimeZone": "Central Standard Time",
  "End": "2015-08-11T15:00:00-05:00",
  "EndTimeZone": "Central Standard Time",
}

json_payload = json.dumps(data)

# Build the HTTP request
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request(url, data=json_payload)
auth = base64.encodestring('%s:%s' % (user, pwd)).replace('\n', '')
request.add_header('Authorization', 'Basic %s' % auth)
request.add_header('Content-Type', 'application/json')
request.add_header('Accept', 'application/json')
request.get_method = lambda: 'POST'
# Perform the request
result = opener.open(request)

Solution

  • I ended up making function to create one event at a time and call the function on each iteration:

    def create_event(date1, date2):
        # Create JSON payload
        data = {
          "Subject": admin.longname,
          "Body": {
            "ContentType": "HTML",
            "Content": ""
          },
          "Start": date1,
          "StartTimeZone": "Central Standard Time",
          "End": date2,
          "EndTimeZone": "Central Standard Time",
        }
    
        json_payload = json.dumps(data)
    
        # Build the HTTP request
        opener = urllib2.build_opener(urllib2.HTTPHandler)
        request = urllib2.Request(url, data=json_payload)
        auth = base64.encodestring('%s:%s' % (user, pwd)).replace('\n', '')
        request.add_header('Authorization', 'Basic %s' % auth)
        request.add_header('Content-Type', 'application/json')
        request.add_header('Accept', 'application/json')
        request.get_method = lambda: 'POST'
        # Perform the request
        result = opener.open(request)
    
    def A( weeka, weekb ):
        today = datetime.date.today()
        firstday = today + relativedelta(weekday=SU(+ weeka))
        for i in range(5):
            firstday += datetime.timedelta(days=1)
            date1 = '%sT07:00:00-05:00' % firstday
            date2 = '%sT16:00:00-05:00' % firstday
            create_event(date1, date2)
    
    A(1,2)