Import JSON object in Google SpreadSheet using Google APP Script - json

I writing a script which calls REST API to get JSON to object as response and then import that JSON object in Google SpreadSheet. I have written the code to call the REST API and get the JSON object. Now I have to write such a code that will write the JSON object in a Google SpreadSheet.
Please see below code:
function myFunction() {
var options = {};
options.headers = {"Authorization": "Basic " + Utilities.base64Encode("username" + ":" + "password")}
options.muteHttpExceptions=true;
// var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
var response=UrlFetchApp.fetch("url", options);
var dataAll=JSON.parse(response.getContentText())
Logger.log(dataAll)
/*
var sheet = Sheets.newSpreadsheet();
sheet.properties = Sheets.newSpreadsheetProperties();
sheet.properties.title = "Demo";
var spreadsheet = Sheets.Spreadsheets.create(sheet);
*/
}
This is code to call get the JSON object. The lines of code which have been commented out is for calling Google Sheets API.
I want such a script which will import the data in dataAll object, which is JSON object in Google SpreadSheet.
The JSON object is as below:
[
{
"id": 3428,
"type": "SUPER",
"firstName": "Nikhil",
"lastName": "Dingane",
"loginName": "nikhildingane",
"domain": "openspecimen",
"emailAddress": "nikhil#krishagni.com",
"instituteName": "Krishagni Institute",
"primarySite": "KSPL site",
"admin": true,
"instituteAdmin": false,
"manageForms": true,
"cpCount": 0,
"creationDate": 1586333347000,
"activityStatus": "Active"
},
{
"id": 3439,
"type": "NONE",
"firstName": "NikhilUpdated",
"lastName": "Dingane",
"loginName": "nikhildingane1",
"domain": "openspecimen",
"emailAddress": "nikhil.nikhil.dingane#gmail.com",
"instituteName": "Krishagni Institute",
"primarySite": "KSPL site",
"admin": false,
"instituteAdmin": false,
"manageForms": true,
"cpCount": 0,
"creationDate": 1586427573000,
"activityStatus": "Active"
}
]
I want to write this JSON in Google SpreadSheet

Assuming that dataAll is a 2D array of values
You can do it is as following with the SpreadsheetApp:
var ss = SpreadsheetApp.getActive();
var sheet = ss.getActiveSheet();
var range = sheet.getRange(1,1, dataAll.length, dataAll[0].length);
range.setValues(dataAll);
References:
SpreadsheetApp
Range
setValues()
How to transform a JSON object into a 2D array
Use the Object.keys() method to access the key-value pairs of each of the JSON array elements
Use e.g. map to transform them into an array
Assemble the single arrays as desired to set them into the sheet
var array = [];
for (var i = 0; i< json.length; i++){
var newJson = Object.keys(json[i]).map(function (key) {
return [key, json[i][key]];
});
for(var j = 0; j< newJson.length; j++){
array.push(newJson[j]);
}
}
var ss = SpreadsheetApp.getActive();
var sheet = ss.getActiveSheet();
var range = sheet.getRange(1,1, array.length, array[0].length);
range.setValues(array);

Range.setValues() is used to the set data as a two dimensional array to the sheet. Use Object.values and Object.keys with Array.map to convert array of objects to 2D array.
const data = [
{
"id": 3428,
"type": "SUPER",
"firstName": "Nikhil",
"lastName": "Dingane",
"loginName": "nikhildingane",
"domain": "openspecimen",
"emailAddress": "nikhil#krishagni.com",
"instituteName": "Krishagni Institute",
"primarySite": "KSPL site",
"admin": true,
"instituteAdmin": false,
"manageForms": true,
"cpCount": 0,
"creationDate": 1586333347000,
"activityStatus": "Active"
},
{
"id": 3439,
"type": "NONE",
"firstName": "NikhilUpdated",
"lastName": "Dingane",
"loginName": "nikhildingane1",
"domain": "openspecimen",
"emailAddress": "nikhil.nikhil.dingane#gmail.com",
"instituteName": "Krishagni Institute",
"primarySite": "KSPL site",
"admin": false,
"instituteAdmin": false,
"manageForms": true,
"cpCount": 0,
"creationDate": 1586427573000,
"activityStatus": "Active"
}
];
const out = [Object.keys(data[0]),...data.map(Object.values)];
console.info(out);
//SpreadsheetApp.getActive().getSheets()[0].getRange(1,1,out. length,out[0].length).setValues(out)

Related

Google app scrips Slack API Get pins:list

Using Google app script as serverless for a slack bot. Having an issue returning specific values from slack API. I'm using the pins:list call. I am able to get the JSON in response and items calls but get null when trying to get the next set of values. I am looking to return "permalinks" so I can then post back into slack what items are pinned to a room. here is my script:(without giving away company details)
function GetPinns() {
const ss = SpreadsheetApp.getActiveSpreadsheet()
let url = "https://slack.com/api/pins.list?channel=C0XXXXXXXXX&pretty=1";
let payload = {
"ok": true,
"channel": "C0XXXXXXXXX"
"type": "message",
}
var options = {
"method": "get",
"payload": JSON.stringify(payload),
"headers": {
"Content-type": "application/json; charset=utf-8",
"Authorization": "Bearer xoxb-"}}
var response = UrlFetchApp.fetch(url, options)
var json = response.getContentText();
var data = JSON.parse(json);
var items = data.item.permalinks;
Logger.log(items);
}
Thank you!!
SUGGESTION
Upon reviewing Slack's official docs for pins.list method, I suppose that this sample JSON response below is the same as the actual JSON response that you're getting:
Sample JSON response:
{
"items": [
{
"channel": "C2U86NC6H",
"created": 1508881078,
"created_by": "U2U85N1RZ",
"message": {
"permalink": "https://hitchhikers.slack.com/archives/C2U86NC6H/p1508197641000151",
"pinned_to": [
"C2U86NC6H"
],
"text": "What is the meaning of life?",
"ts": "1508197641.000151",
"type": "message",
"user": "U2U85N1RZ"
},
"type": "message"
},
{
"channel": "C2U86NC6H",
"created": 1508880991,
"created_by": "U2U85N1RZ",
"message": {
"permalink": "https://hitchhikers.slack.com/archives/C2U86NC6H/p1508284197000015",
"pinned_to": [
"C2U86NC6H"
],
"text": "The meaning of life, the universe, and everything is 42.",
"ts": "1503289197.000015",
"type": "message",
"user": "U2U85N1RZ"
},
"type": "message"
}
],
"ok": true
}
You can try iterating though the items array via looping in the JSON response to get each permalinks data, as seen on this quick test below:
Quick Test
function GetPinns() {
//This sample JSON String response was from https://api.slack.com/methods/pins.list#examples
var json =
"{\"items\": [{\"channel\": \"C2U86NC6H\",\"created\": 1508881078,\"created_by\": \"U2U85N1RZ\",\"message\": {\"permalink\": \"https://hitchhikers.slack.com/archives/C2U86NC6H/p1508197641000151\",\"pinned_to\": [\"C2U86NC6H\"],\"text\": \"What is the meaning of life?\",\"ts\": \"1508197641.000151\",\"type\": \"message\",\"user\": \"U2U85N1RZ\"},\"type\": \"message\"},{\"channel\": \"C2U86NC6H\",\"created\": 1508880991,\"created_by\": \"U2U85N1RZ\",\"message\": {\"permalink\": \"https://hitchhikers.slack.com/archives/C2U86NC6H/p1508284197000015\",\"pinned_to\": [\"C2U86NC6H\"],\"text\": \"The meaning of life, the universe, and everything is 42.\",\"ts\": \"1503289197.000015\",\"type\": \"message\",\"user\": \"U2U85N1RZ\"},\"type\": \"message\"}],\"ok\": true}";
var data = JSON.parse(json);
//Iterate through the items via looping
data.items.forEach(item => {
Logger.log(item.message.permalink)
});
}
Result
Your script will look like this:
function GetPinns() {
const ss = SpreadsheetApp.getActiveSpreadsheet()
let url = "https://slack.com/api/pins.list?channel=C0XXXXXXXXX&pretty=1";
let payload = {
"ok": true,
"channel": "C0XXXXXXXXX"
"type": "message",
}
var options = {
"method": "get",
"payload": JSON.stringify(payload),
"headers": {
"Content-type": "application/json; charset=utf-8",
"Authorization": "Bearer xoxb-"
}
}
var data = JSON.parse(json);
//Iterate through the items via looping
data.items.forEach(item => {
Logger.log(item.message.permalink)
});
}
Reference
https://www.sitepoint.com/loop-through-json-response-javascript/
Thank you!!
I wound up with this in the end
var response = UrlFetchApp.fetch(url, options);
var json = JSON.parse(response.getContentText());
var items = json.items
var linkList = ""
for(var x in items) {
var link = items[x]["message"]["permalink"]
var text = items[x]["message"]["text"]
linkList += "<" + link +"|" + text +">" + "\n"
}

JSON File on Drive to Google sheets

I have a few JSON files on my Google Drive from which I need to extract data into a spreadsheet. I have tried the ImportJson function from github but that is to fetch the JSON file directly from the API but the JSON files I have on my drive are not accessible to me directly from the API.
Can anyone help me in how can I get the JSON stored on the drive to be imported in the Google sheets.
The sample JSON is attached herewith:
{
"gstin": "12ABCDE",
"fp": "082019",
"b2b": [{
"ctin": "2312ABCDEY",
"cfs": "Y",
"cfs3b": "Y",
"inv": [{
"val": 1072,
"itms": [{
"num": 1,
"itm_det": {
"csamt": 0,
"samt": 81.76,
"rt": 18,
"txval": 908.48,
"camt": 81.76
}
}],
"inv_typ": "R",
"pos": "23",
"idt": "02-08-2019",
"rchrg": "N",
"inum": "642",
"chksum": "7a58ec7342001040acf4509176ba22ceb03d9ad0ecf7e74d572af0ec4d8429fa"
}, {
"val": 1072,
"itms": [{
"num": 1,
"itm_det": {
"csamt": 0,
"samt": 81.76,
"rt": 18,
"txval": 908.48,
"camt": 81.76
}
}],
"inv_typ": "R",
"pos": "23",
"idt": "17-08-2019",
"rchrg": "N",
"inum": "722",
"chksum": "0597afa614e27aa78dc252f2530172007e574f52d1ceea9e433e04f474414bbf"
}],
"fldtr1": "10-Sep-19",
"flprdr1": "Aug-19"
}, {
"ctin": "22AAB1Z5",
"cfs": "Y",
"cfs3b": "Y",
"inv": [{
"val": 459463,
"itms": [{
"num": 1801,
"itm_det": {
"csamt": 0,
"rt": 18,
"txval": 389375,
"iamt": 70087.5
}
}],
"inv_typ": "R",
"pos": "23",
"idt": "30-08-2019",
"rchrg": "N",
"inum": "2495",
"chksum": "15ef392cfd4fd3af2fce1ad8549f93bac20cf17308df9bf9256ae838db45a440"
}],
"fldtr1": "11-Sep-19",
"flprdr1": "Aug-19"
}, {
"ctin": "23AFEZI",
"cfs": "Y",
"cfs3b": "Y",
"inv": [{
"val": 9350,
"itms": [{
"num": 1,
"itm_det": {
"csamt": 0,
"samt": 713.16,
"rt": 18,
"txval": 7924,
"camt": 713.16
}
}],
"inv_typ": "R",
"pos": "23",
"idt": "02-08-2019",
"rchrg": "N",
"inum": "00075",
"chksum": "cb4fe40cb2f39f8782a160ece273991daae68b739dfba454ffeb364150d03580"
}, {
"val": 12312,
"itms": [{
"num": 1,
"itm_det": {
"csamt": 0,
"samt": 939.07,
"rt": 18,
"txval": 10434.09,
"camt": 939.07
}
}],
"inv_typ": "R",
"pos": "23",
"idt": "10-08-2019",
"rchrg": "N",
"inum": "00084",
"chksum": "1d0fa36c2a7f1ffe7d7c07a829056e4e28fd0300fd593f91ba8216ace4e54f2a"
}],
"fldtr1": "05-Sep-19",
"flprdr1": "Aug-19"
}, {
"ctin": "23ECVPSQ",
"cfs": "Y",
"cfs3b": "Y",
"inv": [{
"val": 10200,
"itms": [{
"num": 1,
"itm_det": {
"csamt": 0,
"samt": 777.97,
"rt": 18,
"txval": 8644.1,
"camt": 777.97
}
}],
"inv_typ": "R",
"pos": "23",
"idt": "13-08-2019",
"rchrg": "N",
"inum": "650",
"chksum": "43bcf7c73bf94013344111d95c6f80dea47980ef4bfd3093a33e2c385baa2fdd"
}, {
"val": 4745,
"itms": [{
"num": 1,
"itm_det": {
"csamt": 0,
"samt": 361.91,
"rt": 18,
"txval": 4021.18,
"camt": 361.91
}
}],
"inv_typ": "R",
"pos": "23",
"idt": "30-08-2019",
"rchrg": "N",
"inum": "727",
"chksum": "fae1037d879dc718f322e8622a5323344a6cf88b68f68620aaa7ed5d92a15a23"
}]
}
Data sample to look like this
You basically want to retrieve all the nested properties in your object (after you've converted the JSON string using JSON.parse(), and write the corresponding key-value pairs to the first two rows of your spreadsheet (key in row 1, value in row 2). When the value is an object, the key will be written in row 1, but row 2 will remain blank (e.g. b2b).
In this case, you could use recursion to iterate through and retrieve all the nested properties and values from the object. The function could be something like this:
function allProps(element, array, parent = "") {
if (typeof element === 'object' && element !== null) {
if (parent != "") array.push([parent, ""]);
const entries = Object.entries(element);
entries.forEach(entry => {
const nextParent = Array.isArray(element) ? "" : entry[0];
allProps(entry[1], array, nextParent);
});
} else {
array.push([parent, element]);
}
}
The idea is that, for each value, it checks if the value is an object or a primitive data type. If it's the former, allProps gets called recursively, and if it's the latter, the key-value pair is added to the spreadsheet.
And you could call it this way:
function JSON_to_Spreadsheet() {
const id = "JSON_FILE_ID"; // Change to your FILE_ID
const json = DriveApp.getFileById(id).getBlob().getDataAsString(); // Get JSON text from Drive file
const obj = JSON.parse(json); // JSON text to JS object
let array = []; // 2D array where the output will be stored
allProps(obj, array, parent = ""); // Call function recursively
array = array[0].map((_, colIndex) => array.map(row => row[colIndex])); // Transpose 2D array
const sheet = SpreadsheetApp.getActive().getActiveSheet(); // Retrieve active sheet. Change if you want to access another sheet or another spreadsheet
sheet.getRange(1,1,array.length, array[0].length).setValues(array); // Write 2D array to your sheet.
}
The output looks like this:
Edit:
If you want each ctin header (apart from the first one, in column D) to occupy a new row, you can do the following once you have retrieved the 2D array:
Retrieve an array with all the indexes from array[0] where the header is ctin (excluding the first one).
Using these indexes, add each ctin segment to the main array.
Write the array to the sheet, taking into account that the different rows have different lengths. If you wanted to use a single setValues (that would be recommended for efficiency purposes), you'd first have to find the maximum length of the inner array elements, and make all the inner arrays have this length.
The function JSON_to_Spreadsheet could be something like this:
function JSON_to_Spreadsheet() {
const id = "JSON_FILE_ID"; // Change to your FILE_ID
const json = DriveApp.getFileById(id).getBlob().getDataAsString(); // Get JSON text from Drive file
const obj = JSON.parse(json); // JSON text to JS object
let array = []; // 2D array where the output will be stored
allProps(obj, array, parent = ""); // Call function recursively
array = array[0].map((_, colIndex) => array.map(row => row[colIndex])); // Transpose 2D array
const ctinFirstIndex = 3; // Column D (first ctin)
const ctinIndexes = array[0].reduce((acc, current, i) => {
if (current === "ctin" && i !== ctinFirstIndex) {
acc.push(i);
}
return acc;
}, []); // Find indexes for all ctin headers
for (let i = 0; i < ctinIndexes.length; i++) {
[0,1].forEach(rowIndex => {
const sliced = array[rowIndex].slice(ctinIndexes[i], ctinIndexes[i + 1]); // Extract ctin segment
sliced.unshift("","",""); // Columns A to C should be empty
array.push(sliced); // Add each ctin segment to the 2D array
});
}
[0,1].forEach(rowIndex => array[rowIndex].splice(ctinIndexes[0])); // Remove other ctin data from first two rows
const sheet = SpreadsheetApp.getActive().getSheetByName("Copy of Data");
for (let i = 0; i < array.length; i = i + 2) {
sheet.getRange(sheet.getLastRow() + 1, 1, 2, array[i].length).setValues(array.slice(i, i + 2));
} // Write array to sheet. Rows have different dimensions, so cannot be written all at once
}
In this case, the output is:
This should work for a specific json file. Since opening a JSON file in drive is a bit hard to get the file ID you can use the first function to get the ID.
EDIT:
When you run the first function you can look-up the jsonfile ID in the logs -> View -> Log. Then insert this ID in the second function under // Change file id
//With this function you can get the ID of you json file. After running see the view -> Logs for the info.
function getDriveFileID() {
//Change id of the drive folder found in the url
const folderID = "1UN3xxxpE8mXjHHJJF";
const driveFolder = DriveApp.getFolderById(folderID);
const driveFiles = driveFolder.getFiles();
while(driveFiles.hasNext()){
let file = driveFiles.next();
console.log(file.getName()," = ",file.getId());
};
}
function JSON_from_DRIVE() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
//change output sheetname
const sheet = ss.getSheetByName("Data");
//Change file id
const file = DriveApp.getFileById("1IPyU2nxxxxx_lr0F").getBlob().getDataAsString();
const dataAll = JSON.parse(file);
const dataRows = dataAll['b2b'];
const rowHeaders = Object.keys(dataRows[0]);
const rows = [rowHeaders];
for (var i = 0; i < dataRows.length; i++) {
var rowData = [];
for (var j = 0; j < rowHeaders.length; j++) {
rowData.push(dataRows[i][rowHeaders[j]]);
}
rows.push(rowData);
}
sheet.getRange(1,1,rows.length,rows[0].length).setValues(rows);
}
EDIT: this should work custom for your json file.
//With this function you can get the ID of you json file. After running see the view -> Logs for the info.
function getDriveFileID() {
//Change id of the drive folder found in the url
const folderID = "1UN3xxxpE8mXjHHJJF";
const driveFolder = DriveApp.getFolderById(folderID);
const driveFiles = driveFolder.getFiles();
while (driveFiles.hasNext()) {
let file = driveFiles.next();
console.log(file.getName(), " = ", file.getId());
};
}
function JSON_from_DRIVE() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
//change output sheetname
const sheet = ss.getSheetByName("Data");
//Change file id
const file = DriveApp.getFileById("1IPyU2nxxxxx_lr0F").getBlob().getDataAsString();
const dataAll = JSON.parse(file);
const b2b = dataAll['b2b'];
const dataRows = [];
b2b.forEach(base => {
base.inv.forEach(inv => {
const obj = {
"ctin": base.ctin,
"cfs": base.cfs,
"cfs3b": base.cfs3b,
"val": inv.val,
"num": inv.itms[0].itm_det.csamt,
"csamt": inv.itms[0].itm_det.csamt,
"samt": inv.itms[0].itm_det.samt,
"rt": inv.itms[0].itm_det.rt,
"txval": inv.itms[0].itm_det.txval,
"camt": inv.itms[0].itm_det.camt,
"inv_type": inv.inv_typ,
"pos": inv.pos,
"idt": inv.idt,
"rchrg": inv.rchrg,
"inum": inv.inum,
"chksum": inv.chksum,
"fldtr1": base.fldtr1,
"flprdr1": base.flprdr1
}
newObj.push(obj);
});
});
const rowHeaders = Object.keys(dataRows[0]);
const rows = [rowHeaders];
for (var i = 0; i < dataRows.length; i++) {
var rowData = [];
for (var j = 0; j < rowHeaders.length; j++) {
rowData.push(dataRows[i][rowHeaders[j]]);
}
rows.push(rowData);
}
sheet.getRange(1, 1, rows.length, rows[0].length).setValues(rows);
}

Google Apps Script - GoogleJsonResponseException: API call to sheets.spreadsheets.values.update failed with error: Invalid values[1][0]

the goal is to query fields inside a JSON object . But when executed the error above is throwned.
Dialogflow is integrated inside Slack as an App. The Google Apps Script is the web app. Here is the code:
//Writes in a sheet the Slack User id
function doPost(e) {
//Parse incoming JSON from Dialogflow into an object
var dialogflow = JSON.parse(e.postData.contents);
//Extracts userId from Slack
var desiredField = dialogflow.originalDetectIntentRequest.payload.data.event.user;
//Instantiates Sheets function
var valueRange = Sheets.newValueRange();
//Value to insert in cell
var values = [[ desiredField]];
valueRange.values = values;
//Inserts value in cell
var result = Sheets.Spreadsheets.Values.update(valueRange, 'XXX-YYY-ZZZ', 'rangeReceivingData', {valueInputOption: 'RAW'});
}
and here's the incoming JSON:
{
"responseId": "XXX-YYY-ZZZ",
"queryResult": {
"queryText": "oi",
"action": "input.welcome",
"parameters": {
},
"allRequiredParamsPresent": true,
"fulfillmentText": "Oi!",
"fulfillmentMessages": [{
"text": {
"text": ["Oi!"]
}
}],
"outputContexts": [{
"name": "projects/test-agent-xxyy/agent/sessions/xxx-yyy-zzz/contexts/__system_counters__",
"parameters": {
"no-input": 0.0,
"no-match": 0.0
}
}],
"intent": {
"name": "projects/test-agent-xxyy/agent/intents/xxx-yyy-zzz",
"displayName": "Default Welcome Intent"
},
"intentDetectionConfidence": 1.0,
"languageCode": "pt-br"
},
"originalDetectIntentRequest": {
"source": "slack",
"payload": {
"data": {
"event_time": "1589561467",
"api_app_id": "xxxyyyzzz",
"type": "event_callback",
"event": {
"event_ts": "1589561467.000200",
"team": "xxxyyyzzz",
"blocks": [{
"type": "rich_text",
"block_id": "xxxyyyzzz",
"elements": [{
"elements": [{
"text": "oi",
"type": "text"
}],
"type": "rich_text_section"
}]
}],
"ts": "1589561467.000200",
"channel_type": "im",
"client_msg_id": "xxx-yyy-zzz",
"text": "oi",
"type": "message",
"channel": "xxxyyyzzz",
"user": "T1H2E3G4O5A6L7"
},
"authed_users": ["XXXYYYZZZ"],
"event_id": "xxxyyyzzz",
"token": "xxxyyyzzz",
"team_id": "xxxyyyzzz"
}
}
},
"session": "projects/test-agent-xxyy/agent/sessions/xxx-yyy-zzz"
}
also, the fulfillment response in dialogflow have this weird formating:
fields {
key: "action"
value {
string_value: "input.welcome"
}
} ... (this is inside the sheets api error response)
When debuging it was possible to query the respondeId field (the first field from the incoming JSON). It looks that the program is taking lots of processing time on queryng further fields and in the end it throws the error. Any suggestion?
Documentation references:
Writing in Sheets
Handling POST requests in apps scripts
Dialogflow documentation on webhooks
Thanks in advance!
Error, solved. First, point:
It was possible to recover the received JSON from the webhook by using JSON.stringify:
function doPost(e) {
//Parse incoming JSON from Dialogflow
var dialogflow = JSON.parse(e.postData.contents);
//Stringify webhook after parsing
var desiredField = JSON.stringify(dialogflow);
//Outputs value in sheet
var valueRange = Sheets.newValueRange();
//Value to insert in cell
var values = [[ desiredField]];
valueRange.values = values;
//Inserts value in cell
var result = Sheets.Spreadsheets.Values.update(valueRange, 'spreadSheetId', 'range',
{valueInputOption: 'RAW'});
}
The incoming JSON was as expected then it was just a matter of querying the desired field:
from this:
//Stringify webhook after parsing
var desiredField = JSON.stringify(dialogflow);
to this:
//Extracts userId from Slack
var desiredField = dialogflow.originalDetectIntentRequest.payload.data.event.user;
Error solved!

How to Retrieve (not create) Tasks from Asana using Apps Script & Personal Access Token

I am attempting to retrieve, but not create, tasks from Asana using Google Apps Script.
Using the Asana API Explore, I have constructed a URL that returns the data I desire: https://app.asana.com/api/1.0/tasks?opt_fields=name,assignee_status&assignee=987654321987654&completed_since=2018-02-22&limit=100&workspace=456789123456
This URL returns the desired data, in the following format:
{
"data": [
{
"id": 147258369147258,
"assignee_status": "inbox",
"name": "An example task name"
},
{
"id": 963852741963852,
"assignee_status": "upcoming",
"name": "And second example task name."
},
//etc...
]
}
With that URL as a model, I have created a Personal Access Token and executed the following function within Apps Script:
function getTasks5() {
// Asana Personal Token
var bearerToken = "Bearer " + "asdf123456789asdf456789456asdf";
//Request
var request = {
data: {
opt_fields: ["name", "assignee_status"],
assignee: "987654321987654",
completed_since: "2018-02-22",
limit: "100",
workspace: "456789123456"
}
};
// Request options
var options = {
method: "GET",
headers: {
"Authorization": bearerToken
},
contentType: "application/json",
payload: JSON.stringify(request)
};
var url = "https://app.asana.com/api/1.0/tasks";
var result = UrlFetchApp.fetch(url, options);
var reqReturn = result.getContentText();
Logger.log(reqReturn);
}
Instead of returning the desired data as the aforementioned URL does, the function creates an unnamed task in Asana, which is undesirable. It also returns this response containing undesired data:
{
"data": {
"id": 123456789123456,
"created_at": "2018-02-22T20:59:49.642Z",
"modified_at": "2018-02-22T20:59:49.642Z",
"name": "",
"notes": "",
"assignee": {
"id": 987654321987654,
"name": "My Name Here"
},
"completed": false,
"assignee_status": "inbox",
"completed_at": null,
"due_on": null,
"due_at": null,
"projects": [],
"memberships": [],
"tags": [],
"workspace": {
"id": 456789123456,
"name": "Group Name Here"
},
"num_hearts": 0,
"num_likes": 0,
"parent": null,
"hearted": false,
"hearts": [],
"followers": [
{
"id": 987654321987654,
"name": "My Name Here"
}
],
"liked": false,
"likes": []
}
}
Is it possible to simply GET a list of tasks in the manner exemplified by my first JSON example above without creating a task, and without resorting to using OAuth? If so, what changes to the Apps Script function need to be made?
Alright, the problem was with the approach I was taking. Rather than format the request with a payload (which infers a POST request), I needed to structure it more traditionally as a GET request, like so:
var requestUrl = "https://app.asana.com/api/1.0/tasks?opt_fields=name,assignee_status&assignee=123456789123&completed_since=2018-02-22&limit=100&workspace=987654321987";
var headers = {
"Authorization" : "Bearer " + AUTH_TOKEN
};
var reqParams = {
method : "GET",
headers : headers,
muteHttpExceptions: true
};
Then I was able to perform:
UrlFetchApp.fetch(requestUrl, reqParams);
And obtain the data I was after.

Use Mandrill API in Google Apps Script

I want to use mandrill email sending api in my google apps script. In google script I have to use JSON code but I am not getting how I will use it. I am very new in Google apps script.
var m = new mandrill.Mandrill('XXXXXXXXXXX');
var from_email = "user4#gmail.com";
var to = '[
{
"email": "recipient.email#example.com",
"name": "Recipient Name"
}
],';
// create a variable for the API call parameters
var params = {
"message": {
"from_email":from_email,
"to":[{"email":to}],
"subject": "Sending a text email from the Mandrill API",
"text": "I'm learning the Mandrill API at Codecademy, it's very difficult."
}
};
function sendTheMail() {
// Send the email!
alert('this is a mail script');
m.messages.send(params, function(res) {
log(res);
}, function(err) {
log(err);
});
}
I am not getting how to use this code in Google Apps Script.
You'd need to use the urlfetchapp.
var url = "https://mandrillapp.com/api/1.0/messages/send.json";
var your_key = "xxxxxxxxxxxxx";
var from_email = "user4#gmail.com";
var to = [{
"email": "recipient.email#example.com",
"name": "Recipient Name"
}];
var params = {
"key": your_key,
"message": {
"from_email":from_email,
"to":[{"email":to}],
"subject": "Sending a text email from the Mandrill API",
"text": "I'm learning the Mandrill API at Codecademy, it's very difficult."
}
};
var payload = JSON.stringify(params);
var options = {
'method': 'post',
'payload': payload,
'contentType' : 'application/json'
};
var response = UrlFetchApp.fetch(url, options);
Haven't tested this code, but should be something like that.
I paste sample code example to send email by Mandrill with attachment file from Google Drive.
function sendEmail() {
var MANDRILL_API_KEY = "<<your key here>>";
var files = [
"<<Google Drive File ID 1>>",
"<<Google Drive File ID 2>>",
"<<Google Drive File ID 3>>"
];
var recipients = [
{
"email": "ctrlq+to#labnol.org",
"name": "Amit Agarwal",
"type": "to"
}, {
"email": "ctrlq+cc#labnol.org",
"type": "cc"
}, {
"email": "ctrlq+bcc#gmail.com",
"type": "bcc"
}
];
var attachments = [];
for (var f in files) {
var file = DriveApp.getFileById(files[f]);
attachments.push({
"type": file.getMimeType(),
"name": file.getName(),
"content": Utilities.base64Encode(file.getBlob().getBytes())
});
}
var params = {
"key": MANDRILL_API_KEY,
"message": {
"from_email": "<<Sender's Email Address>>",
"from_name": "<<Sender Name>>",
"to": recipients,
"attachments": attachments,
"headers": {
"Reply-To": "reply#example.com"
},
"subject": "Enter email subject",
"text" : "Enter email body in plain text",
"html" : "Enter HTML content with <b>tags</b>"
}
};
var response = UrlFetchApp.fetch(
"https://mandrillapp.com/api/1.0/messages/send.json", {
'method': 'POST',
'payload': JSON.stringify(params),
'contentType': 'application/json'
});
Logger.log(response.getContentText());
}
Sample code is extracted from website ctrlq of Amit Agarwal