The Authentication part of your library is responsible for acquiring authentication and for making authenticated requests. It should not be aware of what is in the requests.
Authentication comes in many forms, but it generally boils down to that each request is accompanied by an
authorization header which contains an access token. The access token is generally a string of random numbers/letters.
Your library should be able to acquire the authentication tokens, update them if necessary and use the authentication to make requests. It should not offer features to store the authentication data.
Because authentication is going to be stored by the developer, it is important that you return the authentication to the developer in a format that can be JSON serializable. A
dict with primitive types (
int) is recommended.
If your API can be served from multiple locations, your authentication class should allow the developer to pass in the location of the API.
Python allows developers to write code that is either synchronous or asynchronous (via
asyncio). Home Assistant is written in async, but is able to work with synchronous libraries too. We prefer async libraries.
If you are writing a library in async, we recommend that you use
aiohttp. It's a modern and mature HTTP library and is easy to use.
To use this class, you will need to create an aiohttp ClientSession and pass it together with the API info to the constructor.
To use this class, construct the class with the API info.
OAuth2 is a standardized version of an authentication schema leveraging refresh and access tokens. The access token expires within a short period of time after being issued. The refresh token can be used to acquire new access tokens.
Refreshing access tokens relies on a client ID and secret, which might be held by an external service. We need to structure the authentication class to be able to allow the developer to implement their own token refresh logic.
Home Assistant ships with the Home Assistant Cloud Account Linking service, a free cloud service to allow users to quickly connect accounts using OAuth2. Home Assistant has easy to use tools built-in to allow users to configure OAuth2-based integrations. For more info, read here. These built-in tools work best if your library is implemented like the examples below.
Now the developer that is using your library will have to implement the abstract method for getting the access token. Let's assume that the developer has their own token manager class.
If you are using
requests, we recommend that you use the
requests_oauthlib package. Below is an example that works with a local client ID and secret but also allows outsourcing token fetching to Home Assistant.
A developer will now be able to override the refresh token function to route it via their own external service.