Search code examples
google-apps-scriptunauthorized

How to convert ajax in javascript to UrlFetchApp in Google script?


I'd like to get data from szimek ad suite api in google script. Here is example to get data from szimek api in javascript.

var settings = {
    "url": "https://adapi.uat.sizmek.com/sas/login/login",
    "method": "POST",
    "timeout": 0,
    "headers": {
        "Content-Type": "application/json",
        "api-key": "api key token",
        "": ""
    },
    "data": "{username:\"Username\", password: \"Password\"}",
};

$.ajax(settings).done(function(response) {
    console.log(response);
});

Szimek api Help

so I converted code in google script.

const API_KEY = '[api token]';
var url = 'https://adapi.sizmek.com/sas/login/login/'

// Make a POST request with a JSON payload.
var data = {
  'username': '[username]',
  'password': '[password]',
};

var options = {
  'method' : 'post',
  'contentType': 'application/json',
  "headers":{
            Authorization: API_KEY
  },
  "payload": JSON.stringify(data),
  'muteHttpExceptions': true
};

var response = UrlFetchApp.fetch(url, options);

But I got unauthorized error. what is the issue?

enter image description here


Solution

  • Although, unfortunately, I cannot test your request, if your top script is correct, I thought that Authorization: API_KEY might be "api-key": "api key token",. So, how about the following modification?

    From:

    "headers":{
              Authorization: API_KEY
    },
    

    To:

    "headers":{ "api-key": "api key token" },
    

    Note:

    • I'm worried that when "": "" is included in the request header, an error might occur.

    • When I saw your top script again, each key of "{username:\"Username\", password: \"Password\"}" is not enclosed by ". I think that if this is correct, I think that "{username:\"Username\", password: \"Password\"}" might not be able to be parsed as a JSON object. But, I'm not sure about the specification of the server side. So, if the above modification was not the direct solution to your issue, please test the following modification.

      • From

          "headers":{
                    Authorization: API_KEY
          },
          "payload": JSON.stringify(data),
        
      • To

          "headers":{ "api-key": "api key token" },
          "payload": "{username:\"Username\", password: \"Password\"}",