Registry / auth-security / requests-oauth2client

requests-oauth2client

JSON →
library1.8.0pypypi✓ verified 87d ago

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-oauth2client
INSTALL
IMPORT
SIG · REQUESTS-OAUTH2CLI
R
requests-oauth2client
auth-securitypythonv1.8.0
Install
3.3s avg
Import
1108ms
Disk
39MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.8.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
installs and imports cleanly · install 0.0s · import 1.153s · 40.4MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 3.3s · import 1.063s · 41MB
39MB installed
● package 39MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

OAuth2Client
from requests_oauth2client import OAuth2Client
ApiClient
from requests_oauth2client import ApiClient
OAuth2ClientCredentialsAuth
from requests_oauth2client import OAuth2ClientCredentialsAuth
OAuth2AuthorizationCodeAuth
from requests_oauth2client import OAuth2AuthorizationCodeAuth
BearerToken
from requests_oauth2client import BearerToken
from requests_oauth2client import BearerAuth
The `BearerAuth` class was removed in v1.6.0; use `BearerToken` directly as a replacement.

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.

import os import requests from requests_oauth2client import OAuth2Client, OAuth2ClientCredentialsAuth # --- Configuration (replace with your actual values or environment variables) --- TOKEN_ENDPOINT = os.environ.get('OAUTH_TOKEN_ENDPOINT', 'https://example.com/oauth/token') CLIENT_ID = os.environ.get('OAUTH_CLIENT_ID', 'your_client_id') CLIENT_SECRET = os.environ.get('OAUTH_CLIENT_SECRET', 'your_client_secret') API_BASE_URL = os.environ.get('API_BASE_URL', 'https://api.example.com') SCOPE = os.environ.get('OAUTH_SCOPE', 'read write') # --- Client Credentials Flow Example --- try: # 1. Initialize the OAuth2Client oauth2client = OAuth2Client( token_endpoint=TOKEN_ENDPOINT, auth=(CLIENT_ID, CLIENT_SECRET) # Client authentication (Basic or Post) ) # 2. Create an OAuth2ClientCredentialsAuth handler auth_handler = OAuth2ClientCredentialsAuth(oauth2client, scope=SCOPE) # 3. Create a requests Session and attach the auth handler session = requests.Session() session.auth = auth_handler # 4. Make an authenticated API request print(f"Attempting to fetch resource from {API_BASE_URL}/data...") response = session.get(f"{API_BASE_URL}/data") response.raise_for_status() # Raise an exception for HTTP errors print("Successfully fetched data:") print(response.json()) except requests.exceptions.RequestException as e: print(f"An HTTP error occurred: {e}") if e.response is not None: print(f"Response Status: {e.response.status_code}") print(f"Response Body: {e.response.text}") except Exception as e: print(f"An unexpected error occurred: {e}")
Debug
Known issues
breakingThe `BearerAuth` class was removed in `v1.6.0`. Direct usage of `BearerToken` as a requests auth handler is the recommended replacement.
fix
Replace `BearerAuth(token)` with `BearerToken(token)` where `BearerToken` is imported from `requests_oauth2client`.
affects: >=1.6.0
breakingThe parameter `bearer_token_class` in `OAuth2Client` was renamed to `token_class` in `v1.6.0`.
fix
Update any `OAuth2Client` initializations to use `token_class` instead of `bearer_token_class` for custom token classes.
affects: >=1.6.0
breakingThe parameter `url` in `ApiClient` methods (e.g., `get`, `post`) was renamed to `path` in `v1.6.0`.
fix
Adjust calls to `ApiClient` methods to use `path` instead of `url` when specifying the endpoint.
affects: >=1.6.0
gotchaPrior to `v1.5.0`, the `expires_in` field in token responses might have been inconsistently handled (e.g., expecting `int` but receiving `str`). This was fixed to properly handle string values.
fix
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.
affects: <1.5.0
gotchaA bug existed prior to `v1.3.0` where the token expiration leeway was reversed, potentially leading to tokens being considered valid for longer or shorter than intended.
fix
Upgrade to `v1.3.0` or newer to ensure correct calculation and application of token expiration leeway.
affects: <1.3.0
gotchaSensitive client credentials (client_id, client_secret) should never be hardcoded or committed to version control. Always use environment variables or a secure secrets management system.
fix
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.
affects: all
Upgrade
Version history
1.8.0latest on PyPI · released Dec 22, 2025
Audit
Dependencies
requestsrequiredCore HTTP client library it builds upon and extends.
attrsrequiredUsed for structured classes and data models.
Agent activity
10 hits · last 30 days
node
8
OpenAI (training)
2
Resources
requests-oauth2client — pip install requests-oauth2client · libregistry