Home > database >  API access works in curl but UrlFetchApp returns 400 Bad Request
API access works in curl but UrlFetchApp returns 400 Bad Request

Time:07-15

I'm trying to access my Home Assistant API and it works fine using curl, but not in Google Apps Script using UrlFetchApp. Using curl works fine:

curl -X GET -H "Authorization: Bearer longFunkyCodeLikeThisiJ9.eyJpc3Mijk5fQ.0Fpw8I" -H "Content-Type: application/json" https://mydevice.duckdns.org:8123/api/states/sensor.my_special_sensor

Google Apps Script returns a 400 Bad Request error.

var HOME_ASSISTANT_TOKEN = "longFunkyCodeLikeThisiJ9.eyJpc3Mijk5fQ.0Fpw8I"
var HOME_ASSISTANT_URL = "https://mydevice.duckdns.org:8123/api/"

function testTemp() {
  console.log(getDeviceParameters('sensor.my_special_sensor'));
}

function getDeviceParameters(id) {
  var url = HOME_ASSISTANT_URL   "states/"   id;
  Logger.log(url);
  var bearer = "Bearer "   HOME_ASSISTANT_TOKEN;
  var headers = {
    "Authorization": bearer,
    "Content-Type": 'application/json',
  };
  var params = {
    method: 'get',
    headers: headers
  };
  return UrlFetchApp.fetch(url, params ).getContentText();
}

What am I doing wrong?

CodePudding user response:

It seems Google Apps Script may be blocking port 8123. The script functions by using by instead using your nabu casa url which operates out of port 80.

Just change the HOME_ASSISTANT_URL value to https://[yourspecialcode].ui.nabu.casa/api/

  • Related