Requests Session for OAuth 2 Client Credentials Flow with AuthlibApril 4, 2020
Lately I've been writing a lot of background jobs that need to interact with different OAuth 2 service providers. Not knowing any better, I coded my own authorization logic using the Requests library. This approach works, but there's a better solution.
The trick is using a Session object.
In Requests, Session objects allow you to abstract away things that are common to your API calls (such as authorization).
Luckily for us, Authlib comes with its own OAuth 2 Session included.
This session object can be used the same way as the main Requests API:
The difference is, the session will automatically fetch the access token and attach it to every subsequent request.
No need to add an Authorization header to every single API call anymore.