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?
Actually there were multiple issues with the code:
The url
didn't contain the proper Google Calendar API key
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);
}
}