requests-oauth2client is an OAuth 2.x client for Python that leverages the popular `requests` HTTP library. It's designed to obtain, refresh, and revoke tokens from any OAuth2.x/OIDC compliant Authorization Server, supporting various grant types like Client Credentials, Authorization Code, Refresh Token, Token Exchange, JWT Bearer, Device Authorization, Resource Owner Password, and CIBA. The library simplifies OAuth2 interactions by integrating as a `requests` Auth Handler, automatically managing token lifecycle. It is currently at version 1.8.0 and receives regular updates.
pip install requests-oauth2clientVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates the Client Credentials flow using `requests-oauth2client`. It initializes an `OAuth2Client`, creates an `OAuth2ClientCredentialsAuth` handler, and attaches it to a `requests.Session`. The session then automatically handles obtaining, caching, and refreshing the access token for subsequent API calls to a protected resource. Replace placeholder URLs and credentials with your actual values, preferably using environment variables for sensitive data.
Replace `BearerAuth(token)` with `BearerToken(token)` where `BearerToken` is imported from `requests_oauth2client`.
Update any `OAuth2Client` initializations to use `token_class` instead of `bearer_token_class` for custom token classes.
Adjust calls to `ApiClient` methods to use `path` instead of `url` when specifying the endpoint.
Ensure you are on `v1.5.0` or newer for robust handling of `expires_in` values from the authorization server. If on older versions, be prepared for potential type mismatches.
Upgrade to `v1.3.0` or newer to ensure correct calculation and application of token expiration leeway.
Store `CLIENT_ID` and `CLIENT_SECRET` in environment variables (e.g., `os.environ.get('CLIENT_ID')`) or a dedicated secret management solution. This is an OAuth2 security best practice.