简体   繁体   中英

Authorization error with Google apps script

I'm not experienced with Google Apps script. I need to communicate with an external API but keep getting {"error":"Authentication failed"} response.

I appreciate if someone could give me a hint what should I change in my code. I think that I have written the Authorization part wrong (in API documentation is written: Authorization: WebpageToken realm="api", apikey="testkey123")

Below is the API documentation which I'm trying to get to work.

“API-documentation: Some interface functions: commitments, employees, corporates, customers/:id

API communication is done by RESTful-type HTTPS requests which are sent to: https://the.webpage.com/ {CUSTOMER_ID}/api/{ENDPOINT} Where {CUSTOMER_ID} is personal ID and {ENDPOINT} is interface function. The response format is JSON.

Example request (from documentation):

GET /1200/api/customers/1 HTTP/1.1
Host: the.webpage.com
Accept: application/json
Authorization: WebpageToken realm="api", apikey="testkey123"

I have tried to find correct way of writing the authorization by searching from stackoverflow and documentation but with bad luck.

MY CODE in Google Apps Script:

function getCorporates(){
  var ENDPOINT = "corporates";
  var apiKey = ”testkey123”; //example
  var CUSTOMER_ID = 1234; //example

  var options = {
    "method":"GET",
    "muteHttpExceptions": true,
    "Authorization":{
      "WebpageToken":{
        "realm":"api",
        "apikey" :apiKey     
         }
    }
  };
  var url = "https://the.webpage.com/" + CUSTOMER_ID + "/api/" + ENDPOINT;
  var response = UrlFetchApp.fetch(url, options); // get api endpoint
  var json = response.getContentText(); // get the response content as text
  Logger.log(json); //log data to logger to check
}

This code should return a JSON object. Currently I'm receiving {"error":"Authentication failed"} response.

Please note that I had to "hide" the company name so in this case it's changed to the.webpage.com which is not the real API address which I try to call.

Thanks for help!

You need to add the Authorization as a header , which is done like so:

var headers = {
  "Authorization" : "Webpage realm='api', apikey='testkey123'"
};

var params = {
  "method": "GET",
  "muteHttpExceptions": true,
  "headers": headers
};

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

In other words the HTTP headers are their own object within the params object (from my example, options from your example).

See the documentation [0] under 'Advanced Parameters'

[0] https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetch(String,Object)

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