Home > Software engineering >  REST api add body for authorization in google app scripts
REST api add body for authorization in google app scripts

Time:08-22

I am using google app scripts, trying to log in, get token and then get my data with this API: https://www.sensorpush.com/gateway-cloud-api Couldn't understand the syntax required to login and get the token, this is my code:

function restAPI() {
  var scriptProperties = PropertiesService.getScriptProperties();
  var username = scriptProperties.getProperty("username");
  var password = scriptProperties.getProperty("password");
  var options = {'muteHttpExceptions': true};
  var url = 'https://api.sensorpush.com/api/v1/oauth/authorize'
  var response = UrlFetchApp.fetch(url, options);
  Logger.log(response);
}

Obviously I get an error:

{"message": "Missing Authentication Token", "type": "MISSING_AUTHENTICATION_TOKEN", "statusCode": "400" }

CodePudding user response:

I believe your goal is as follows.

  • From the endpoint of your showing script and your provided official document, you want to convert the following curl command to Google Apps Script.

      curl -X POST "https://api.sensorpush.com/api/v1/oauth/authorize" \
      -H "accept: application/json" \
      -H "Content-Type: application/json" \
      -d @- <<BODY
      { 
         "email": "<email>", 
         "password": "<password>"
      } 
      BODY
    

In this case, how about the following modification?

From the sample curl command, it seems that the request body is {"email": "<email>","password": "<password>"}, and this is required to be sent as application/json.

Modified script:

function restAPI() {
  var scriptProperties = PropertiesService.getScriptProperties();
  var username = scriptProperties.getProperty("username");
  var password = scriptProperties.getProperty("password");
  var options = {
    method: "post",
    contentType: "application/json",
    payload: JSON.stringify({ email: username, password: password }),
    headers: { accept: "application/json" }
  };
  var url = 'https://api.sensorpush.com/api/v1/oauth/authorize';
  var response = UrlFetchApp.fetch(url, options);
  Logger.log(response);
}
  • In this modification, it supposes that the value of username is your email address. And also, it supposes that the values of username and password are valid values. Please be careful about this.
  • I think that the request for this modified script is the same as the above curl command. But, if an error occurs, please confirm your values of username and password again.

Reference:

  • Related