简体   繁体   中英

How to use POST and GET request to PARSE platform REST API using Google Apps Script

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

Basically, I made 2 program :

  • One program called "InsertIntoPArse" which allows me to send requests to my parse platform. It has 3 inputs : the Method (POST or GET) the Class that we want to read/modify (table of the database) and the Script to consider.
  • One programme used to build the Script, call "InsertIntoParse" and get the result back.
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 :

  • In the above code you will need to customize the two variables API_KEY and applicationId with your own values. You will also have to customize the variable "root" with the URL of your parse platform (mine is hosted by Amazon Web Services).
  • The query is sent to your Parse platform server using the function UrlFetchApp.fetch. This function has 2 inputs : the url to contact and an additional variable containing the parameters. According to the method you will use (GET or POST) the URL and the parameters will be different:
  • for a POST method, the url will be something like "http://MyParsePlatform.com:80/parse/classes/MyCustomClassName/" and the parameters will contain a line called "payload" in which you will specify the criteria of the object you want to create
  • for a GET method, the parameter will have an exmpty payload and the url will be something like "http://MyParsePlatform.com:80/classes/List?where={"MyColumnName":"Value"}" BUT since a URL can't have special characters like {} and ", we will need to replace these with html codes (%22 for ", %7B for { etc.). One last thing: the equal after the "where" needs to stay an = and shall not be replaced by %3D.

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 :

  • The variable "obj" contains the search criteria of my GET
  • In the "scriptGetFamille" variable definition I use the function "encodeURIComponent" to replace all special characters to HTML codes. Please note that the "where=" is not in this function to avoid the replacemenbt of the = by its HTML equivalent code when using the function "encodeURIComponent".
  • The variable "retourGetFamille" will get the result of the query.

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 :

  • The "scriptFamille" variable allows me to define the characteristics of the object I will create (value for the different columns of the class). Please note the use of the \\ (escape character) used to make sure that the following " character will not close the string.
  • The variable retourFamille will get the result of the request. It will be a JSON object containing the ObjectId and the date of creation of the new object.
  • To get back in a string variable the ObjectId, we need first to parse the response of the API (see the content of the "JSONresponse" variable) and then get the Object Id value using JSONresponse.objectId

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 !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM