{"id":6221,"library":"requests-oauth2client","title":"requests-oauth2client","description":"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.","status":"active","version":"1.8.0","language":"en","source_language":"en","source_url":"https://github.com/guillp/requests_oauth2client","tags":["oauth2","oidc","requests","authentication","authorization","client","token"],"install":[{"cmd":"pip install requests-oauth2client","lang":"bash","label":"Install latest version"}],"dependencies":[{"reason":"Core HTTP client library it builds upon and extends.","package":"requests"},{"reason":"Used for structured classes and data models.","package":"attrs","optional":false}],"imports":[{"symbol":"OAuth2Client","correct":"from requests_oauth2client import OAuth2Client"},{"symbol":"ApiClient","correct":"from requests_oauth2client import ApiClient"},{"symbol":"OAuth2ClientCredentialsAuth","correct":"from requests_oauth2client import OAuth2ClientCredentialsAuth"},{"symbol":"OAuth2AuthorizationCodeAuth","correct":"from requests_oauth2client import OAuth2AuthorizationCodeAuth"},{"note":"The `BearerAuth` class was removed in v1.6.0; use `BearerToken` directly as a replacement.","wrong":"from requests_oauth2client import BearerAuth","symbol":"BearerToken","correct":"from requests_oauth2client import BearerToken"}],"quickstart":{"code":"import os\nimport requests\nfrom requests_oauth2client import OAuth2Client, OAuth2ClientCredentialsAuth\n\n# --- Configuration (replace with your actual values or environment variables) ---\nTOKEN_ENDPOINT = os.environ.get('OAUTH_TOKEN_ENDPOINT', 'https://example.com/oauth/token')\nCLIENT_ID = os.environ.get('OAUTH_CLIENT_ID', 'your_client_id')\nCLIENT_SECRET = os.environ.get('OAUTH_CLIENT_SECRET', 'your_client_secret')\nAPI_BASE_URL = os.environ.get('API_BASE_URL', 'https://api.example.com')\nSCOPE = os.environ.get('OAUTH_SCOPE', 'read write')\n\n# --- Client Credentials Flow Example ---\n\ntry:\n    # 1. Initialize the OAuth2Client\n    oauth2client = OAuth2Client(\n        token_endpoint=TOKEN_ENDPOINT,\n        auth=(CLIENT_ID, CLIENT_SECRET) # Client authentication (Basic or Post)\n    )\n\n    # 2. Create an OAuth2ClientCredentialsAuth handler\n    auth_handler = OAuth2ClientCredentialsAuth(oauth2client, scope=SCOPE)\n\n    # 3. Create a requests Session and attach the auth handler\n    session = requests.Session()\n    session.auth = auth_handler\n\n    # 4. Make an authenticated API request\n    print(f\"Attempting to fetch resource from {API_BASE_URL}/data...\")\n    response = session.get(f\"{API_BASE_URL}/data\")\n    response.raise_for_status() # Raise an exception for HTTP errors\n\n    print(\"Successfully fetched data:\")\n    print(response.json())\n\nexcept requests.exceptions.RequestException as e:\n    print(f\"An HTTP error occurred: {e}\")\n    if e.response is not None:\n        print(f\"Response Status: {e.response.status_code}\")\n        print(f\"Response Body: {e.response.text}\")\nexcept Exception as e:\n    print(f\"An unexpected error occurred: {e}\")\n","lang":"python","description":"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."},"warnings":[{"fix":"Replace `BearerAuth(token)` with `BearerToken(token)` where `BearerToken` is imported from `requests_oauth2client`.","message":"The `BearerAuth` class was removed in `v1.6.0`. Direct usage of `BearerToken` as a requests auth handler is the recommended replacement.","severity":"breaking","affected_versions":">=1.6.0"},{"fix":"Update any `OAuth2Client` initializations to use `token_class` instead of `bearer_token_class` for custom token classes.","message":"The parameter `bearer_token_class` in `OAuth2Client` was renamed to `token_class` in `v1.6.0`.","severity":"breaking","affected_versions":">=1.6.0"},{"fix":"Adjust calls to `ApiClient` methods to use `path` instead of `url` when specifying the endpoint.","message":"The parameter `url` in `ApiClient` methods (e.g., `get`, `post`) was renamed to `path` in `v1.6.0`.","severity":"breaking","affected_versions":">=1.6.0"},{"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.","message":"Prior 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.","severity":"gotcha","affected_versions":"<1.5.0"},{"fix":"Upgrade to `v1.3.0` or newer to ensure correct calculation and application of token expiration leeway.","message":"A 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.","severity":"gotcha","affected_versions":"<1.3.0"},{"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.","message":"Sensitive 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.","severity":"gotcha","affected_versions":"all"}],"env_vars":null,"last_verified":"2026-04-14T00:00:00.000Z","next_check":"2026-07-13T00:00:00.000Z","problems":[]}