How to get an authentication from a rest api using a sensor

I have created several sensors using the rest platform in my sensors.yaml file.

One of them is giving me a hard time authenticating. It requires a registration with a client-id and a secret, this gives me access to fetching a token every hour that I can use for the next API call, to get data.

The API call works when I use postman, and I have tried to change both secret and client-id many times.
I also tried to send the parameters as a payload and typing in client-id and secret in clear and urlencoded text. The results are the same.
I have searched the community and the web, I have read the documentation, but I am not able to see any glitches.

The code looks like this:

- platform: rest
  name: bw_auth
  resource: https://id.barentswatch.no/connect/token
  method: POST
  scan_interval: 3600
  headers:
    User-Agent: Home Assistant
    Content-Type: application/x-www-form-urlencoded
    grant_type: client_credentials
    client_id: !secret bw_clientid
    client_secret: !secret bw_client_secret
    scope: api
  value_template: Bearer {{value_json.access_token}}

I am planning to use the access token I get in the sensor value as input to another sensor to authenticate in another API to actually get data from it (I don’t know if this works yet).

The answer I get in the {{value_json}} in HA is either {'error': 'invalid_client'} or - when I skip some of the other mandatory fields, {'error': 'invalid_request'}

I guess there is something I should change in the code. Are any of you able to see what that is?

…or do you know if there is any debugging options I could use to see what is sent towards the API?

…or do you have any other idea on what I should consider testing?

Thanks!

Ps: The data I plan to get from the next api call is the forecasted wave height on my favourite fishing place. I use this all the time on a different website, but the data is far better than the UI, so I’ll have to fix it myself :slight_smile:

I had a similar issue, but tackled it with NodeRed

Let me know if you want the template :wink:

1 Like