Home > Software engineering >  "401 Error Code" using google script app fetch post
"401 Error Code" using google script app fetch post

Time:05-11

Hi everyone recently i have been trying to do a fetch post in app script, from an api called salesbinder(inventory system), i have managed to fetch and pulls all inventory data down, however i have been struggling to post and add document to it and received an error code ->

"Truncated server response: {"message":"Unauthorized","url":"\/api\/2.0\/documents.json","code":401}"

since I am using the same username and password I can assure that the details are correct for the authentication, would appreciate a lot if anyone could help me to solve the problem.

Here are the api documentaion (https://www.salesbinder.com/api/documents/add/) and the code i have been using.

  function posting(){
  var Username = "{API KEY}"
  var Password = "x"
  var headers = {
    "Authorization" : "Basic "   Utilities.base64Encode(Username  ':'   Password)
  };

  var url ='{API URL}'

  var data ={
    "document":{ 
      "customer_id": 'a93a9e9a-5837-4ec5-9dc7-47cc8cfd84e4',
      "issue_date":"2022-05-09",
      "context_id":5,
      "document_items":[  
          {  
              "quantity":2,
              "price":134,
              "item_id":"   b04993fe-7b17-42a1-b5e5-2d34890794c9"
          }
        ]
      },

    };

  var option = {
    "method": "post",
    'payload' : data,
    "headers": {headers},
  };


  UrlFetchApp.fetch(url, option);
 

}

CodePudding user response:

I think that your error message of "message":"Unauthorized" is due to "headers": {headers},. This has already been mentioned in chrisg86's comment.

And also, from this document, it seems that the request body is required to be sent with Content-Type: application/json.

From:

var option = {
  "method": "post",
  'payload' : data,
  "headers": {headers},
};

To:

var option = {
  "method": "post",
  "payload": JSON.stringify(data),
  headers, // or "headers": headers
  "contentType": "application/json"
};

Note:

  • In this modification, it supposes that the values of "Basic " Utilities.base64Encode(Username ':' Password), data and url are correct. Please be careful this.
  • Related