Bendegúz Csirmaz

Requests Session for OAuth 2 Client Credentials Flow with Authlib

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 OAuth2Session class included.

from authlib.integrations.requests_client import OAuth2Session

session = OAuth2Session(
    client_id="<client id>",
    client_secret="<client secret>",
    scope="<scope 1> <scope 2> etc.",
    token_endpoint="<token endpoint>",
    token={"access_token": None, "expires_in": -100},

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.