requests-oauth2client

1.8.0 · active · verified Tue Apr 14

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.

Warnings

Install

Imports

Quickstart

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}")

view raw JSON →