Error using authorization headers with POST request

I am trying to get JSON from Home Assistant using Request. If I use a GET method it works, but any POST method returns 401 Not Authorized. Whereas both work fine in Postman.

I can see I’m getting a 401 if I use load() instead of loadJSON() and then dump the response. The Home Assistant API documentation shows /api/states is a GET and /api/config/core/check_config is a POST.

Does anybody have thoughts as to what I’m doing wrong?

So this code works:

  let req = new Request(`${config.haUrl}/api/states`)
  req.headers = { 
    "Authorization": `Bearer ${config.haToken}`, 
    "content-type": "application/json" 
  }
  return await req.loadJSON()

But this code does not (it does not require a body), although it does work in Postman:

  let req = new Request(`${config.haUrl}/api/config/core/check_config`)
  req.method = "POST"
  req.headers = { 
    "Authorization": `Bearer ${config.haToken}`, 
    "content-type": "application/json"
  }
  return await req.loadJSON()

In Postman I get the expected JSON result:

{
    "result": "valid",
    "errors": null,
    "warnings": null
}

Whereas using load() or loadString() to see the error in Scriptable I get the following which has status code 401 towards the end:

{"headers":{"Date":"Fri, 08 Mar 2024 09:42:20 GMT","Alt-Svc":"h3=\":443\"; ma=86400","cf-cache-status":"DYNAMIC","Content-Length":"17","referrer-policy":"no-referrer","Server":"cloudflare","report-to":"{\"endpoints\":[{\"url\":\"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?somestuff"}],\"group\":\"cf-nel\",\"max_age\":604800}","Content-Type":"text/plain; charset=utf-8","nel":"{\"success_fraction\":0,\"report_to\":\"cf-nel\",\"max_age\":604800}","x-frame-options":"SAMEORIGIN","cf-ray":"8611dfe7c9d5508b-AKL","x-content-type-options":"nosniff"},"mimeType":"text/plain","url":"https://mydomain/api/config/core/check_config","statusCode":401,"cookies":null,"textEncodingName":"utf-8"}

I tried this code and it works perfectly fine. Try some of the following

  • The Content-Type is set to application/json. Try adding an empty JSON as the body – req.body = '{}'
  • Try regenerating your HA token
  • See if you can find logs on Cloudflare (CF). Seems like your HA instance is behind CF so maybe it’s blocking it rather than HA itself.

Thanks for trying it - at least it proved the problem was mine and not a bug, and helped me solve it.

I don’t think it’s very well documented in Home Assistant, but the endpoints I am posting to (check_config and template) require the token to be associated with a login that is in the Administrators group, not just the Users group.

When I was trying it in Postman I was creating a temporary token rather than having a real token on the web, and that was created by an admin user.

It works after changing the associated user to be an Administrator.