requests-auth

8.0.0 · active · verified Thu Apr 16

requests-auth provides a collection of authentication classes that extend the capabilities of the popular Python `requests` library. It simplifies the implementation of various authentication schemes like OAuth2 (Authorization Code, Client Credentials, PKCE), Okta, Microsoft Entra ID (formerly Azure Active Directory), API Key, Basic, and NTLM. The current version is 8.0.0, released on June 18, 2024, and it typically follows the release cadence of its underlying `requests` and `requests-oauthlib` dependencies, with new features and bug fixes released as needed.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `requests-auth` for three common authentication patterns: OAuth2 Client Credentials flow, API Key in a header, and Bearer Token authentication. It retrieves sensitive credentials from environment variables for security. Ensure you replace placeholder URLs and environment variable names with your actual API details.

import requests
import os
from requests_auth import OAuth2ClientCredentials

# --- Client Credentials Flow Example ---
# Replace with your actual client_id, client_secret, token_url, and API endpoint
CLIENT_ID = os.environ.get('OAUTH_CLIENT_ID', 'your_client_id')
CLIENT_SECRET = os.environ.get('OAUTH_CLIENT_SECRET', 'your_client_secret')
TOKEN_URL = os.environ.get('OAUTH_TOKEN_URL', 'https://example.com/oauth/token')
API_ENDPOINT = os.environ.get('API_ENDPOINT', 'https://api.example.com/data')

if CLIENT_ID and CLIENT_SECRET and TOKEN_URL and API_ENDPOINT:
    try:
        # Initialize OAuth2ClientCredentials auth
        auth = OAuth2ClientCredentials(
            token_url=TOKEN_URL,
            client_id=CLIENT_ID,
            client_secret=CLIENT_SECRET
        )

        # Make an authenticated request
        response = requests.get(API_ENDPOINT, auth=auth)
        response.raise_for_status() # Raise an exception for HTTP errors
        print(f"Client Credentials API Response: {response.json()}")
    except requests.exceptions.HTTPError as e:
        print(f"Client Credentials HTTP Error: {e.response.status_code} - {e.response.text}")
    except Exception as e:
        print(f"An error occurred during Client Credentials flow: {e}")
else:
    print("Skipping Client Credentials example: Environment variables for client ID, secret, token URL, or API endpoint are not set.")

# --- API Key in Header Example ---
# Replace with your actual API key and endpoint
API_KEY_HEADER = os.environ.get('API_KEY_HEADER', 'your_api_key_value')
API_KEY_HEADER_NAME = 'X-API-Key'
API_ENDPOINT_HEADER = os.environ.get('API_ENDPOINT_HEADER', 'https://api.example.com/header-data')

if API_KEY_HEADER and API_ENDPOINT_HEADER:
    try:
        # Initialize ApiKeyAuth for header
        auth_header = ApiKeyAuth(
            API_KEY_HEADER, 
            API_KEY_HEADER_NAME, 
            'header'
        )

        response_header = requests.get(API_ENDPOINT_HEADER, auth=auth_header)
        response_header.raise_for_status()
        print(f"API Key (Header) API Response: {response_header.json()}")
    except requests.exceptions.HTTPError as e:
        print(f"API Key (Header) HTTP Error: {e.response.status_code} - {e.response.text}")
    except Exception as e:
        print(f"An error occurred during API Key (Header) example: {e}")
else:
    print("Skipping API Key (Header) example: Environment variables for API key or endpoint are not set.")

# --- Bearer Token Auth Example (using a pre-obtained token) ---
# In a real application, this token would typically come from an OAuth2 flow.
BEARER_TOKEN = os.environ.get('BEARER_TOKEN', 'your_bearer_token')
API_ENDPOINT_BEARER = os.environ.get('API_ENDPOINT_BEARER', 'https://api.example.com/bearer-data')

if BEARER_TOKEN and API_ENDPOINT_BEARER:
    try:
        # Initialize BearerTokenAuth
        bearer_auth = BearerTokenAuth(BEARER_TOKEN)

        response_bearer = requests.get(API_ENDPOINT_BEARER, auth=bearer_auth)
        response_bearer.raise_for_status()
        print(f"Bearer Token API Response: {response_bearer.json()}")
    except requests.exceptions.HTTPError as e:
        print(f"Bearer Token HTTP Error: {e.response.status_code} - {e.response.text}")
    except Exception as e:
        print(f"An error occurred during Bearer Token example: {e}")
else:
    print("Skipping Bearer Token example: Environment variables for bearer token or endpoint are not set.")

view raw JSON →