Reputation: 11
I'm quite a beginner when it comes to use APIs and recently I spend a lot of time trying to use the Parse Platform API to synchronize it with my Google Spreadsheet. I am struggling to format my GET
or POST
request with UrlfetchApp. How do I issue POST and GET request to PARSE platform REST API using Google Apps Script?
Now that I succeded, I just wish to share my script so it can help other people. See my own answer below
Upvotes: 0
Views: 759
Reputation: 11
Basically, I made 2 program :
var API_KEY = 'Insert Here your API KEY';
var applicationId = 'Insert here your application Id';
function InsertIntoParse(Method, Class, Script) {
var root =
'http://ec2-99-999-999-99.us-east-2.compute.amazonaws.com:80/parse';
var endpoint = '/classes/' + Class;
if (Method == 'POST') {
endpoint = endpoint + '/';
} else if (Method == 'GET') {
var GetScript = Script;
Script = '';
endpoint = endpoint + '?' + GetScript;
}
var params = {
method: Method,
muteHttpExceptions: true,
headers: {
'Content-Type': 'application/json',
'X-Parse-Application-Id': applicationId,
'X-Parse-REST-API-Key': API_KEY,
},
payload: Script,
};
var response = UrlFetchApp.fetch(root + endpoint, params);
//var data = response.getContentText();
//var json = JSON.parse(data);
//var campaigns = json['campaigns'];
Logger.log('response = ' + response);
return response;
}
Here are some explanations :
Please note that if you sent a GET request with a payload, parse will consider it as a POST and will create a new element in your class.
Here is the second program calling "InsertIntoParse" for a GET request :
function GetExample() {
var obj='{"fam_commune":"ANTIBES"}'
var scriptGetFamille = 'where='+encodeURIComponent(obj);
var retourGetFamille=InsertIntoParse('GET','MyClassName',scriptGetFamille);
var JSONresponse = JSON.parse(retourGetFamille.getContentText());
}
Some explanations :
Now let's see an example of POST:
function AddAdherent(NumLigne) {
scriptFamille="{\"MyColumnName1\": \"MyValueForColumn1\",\"MyColumnName2\": \"MyValueForColumn2\"}"
var retourFamille=InsertIntoParse('POST','MyCustomClassName',scriptFamille);
var JSONresponse = JSON.parse(retourFamille.getContentText());
var fam_cd=JSONresponse.objectId;
}
Here are some explanations :
PS: please note that my example above is far from being perfect, especially because I am not using an https connexion (I did not set the https yet on my Parse Platform Server, which is mandatory for the safety of data exchange)
I hope all this will help people and make your life easier. Good luck !
Upvotes: 1