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: