Integration Python API Wrapper

Hi,

Happy New Year to you all.

I am looking at creating a new integration but I am struggling to wrap my head around how to handle authorisation and reauthorisation to the API my integration will use.

I have read the developer documentation for “Building a Python library for an API” (https://developers.home-assistant.io/docs/api_lib_index) and the “Building Integrations” section but I am still struggling and looking for some pointers/examples.

The API that my integration will use needs a POST request to a login URL with a JSON data payload or username and password which will return a JSON Web Token (JWT) which is valid for 60minutes. The JWT needs to be sent as bearer token with each request in order to use the API. When the JWT expires another POST request needs to be made to the login URL containing a username and password in order to obtain a new JWT which can be used for requests. I get that this is all pretty standard stuff.

How do I handle the token expiration and renewal?

My guess that Home Assistant will handle this but I’m not sure how to implement this in my integration.

Any help would be appreciated.

Actually the python library should probably handle it.

Basically, HA send whatever request it is wanting to make to the library. The library trys to make a request to the API, and gets a 401 back. If you get a 401 then you attempt to get a new token and then make the request again automatically.

This library is far from great, but it does what you are asking and is used by HA, so maybe check it out.