0

I've created a bot via Hangouts API and now would like to send a POST request to Google Calendar API (Freebusy: query) via Google Scripts console:

function testPOST() {

    const url = "https://www.googleapis.com/calendar/v3/freeBusy";

    const datetimeMin = "2018-02-22T18:00:00.000Z";
    const datetimeMax = "2018-02-22T20:00:00.000Z";

    const payload = {
        calendarExpansionMax: 5,
        groupExpansionMax: 2,
        items: [{
            id: "%my_email@gmail.com%"
        }],
        timeMax: datetimeMax,
        timeMin: datetimeMin,
        timeZone: "Europe/Paris"
    }

    const options = {
        followRedirects: true,
        method: "POST",
        muteHttpExceptions: true,
        payload: payload
    };

    const result = UrlFetchApp.fetch(url, options);

    if (result.getResponseCode() == 200) {
        const params = JSON.parse(result.getContentText());
        Logger.log(params.name);
        Logger.log(params.blog);
    } else {
        Logger.log(result);
    }
}

During execution result is null or undefined, Google Console shows this object but it's empty. I checked, the default calendar of the specified email is public.

How to send a POST-request from Hangouts API via Google Scripts console?

Mike
  • 14,010
  • 29
  • 101
  • 161

2 Answers2

2

The Calendar API endpoint probably expects the payload to be a JSON encoded string. So update your options object as follows:

var options = {
    "method":"POST",
    "contentType":"application/json",
    "payload":JSON.stringify(payload)
}
TheAddonDepot
  • 8,408
  • 2
  • 20
  • 30
1

Actually there were multiple issues with the code:

  1. The url didn't contain the proper Google Calendar API key

  2. The result has not been parsed to JSON

The correct code:

function testPOST() {

    const url = 'https://www.googleapis.com/calendar/v3/freeBusy?key=%GOOGLE_CALENDAR_API_KEY%';

    const datetimeMin = "2018-02-22T18:00:00.000Z";
    const datetimeMax = "2018-02-22T20:00:00.000Z";

    const payload = {
        calendarExpansionMax: 5,
        groupExpansionMax: 2,
        items: [{
            id: "%my_email@gmail.com%"
        }],
        timeMax: datetimeMax,
        timeMin: datetimeMin,
        timeZone: "Europe/Paris"
    }

    const options = {
        contentType: "application/json",
        method: "POST",
        muteHttpExceptions: true,
        payload: JSON.stringify(payload),
        timeZone: "CEST",
    };

    const result = UrlFetchApp.fetch(url, options);
    
    Logger.log(result);
    
    if (result.getResponseCode() == 200) {
        const params = JSON.parse(result.getContentText());
        Logger.log(params.name);
        Logger.log(params.blog);
    } else {
        Logger.log(result);
    }
}
Mike
  • 14,010
  • 29
  • 101
  • 161