import requests import os CLIENT_ID = os.getenv('OAUTH_CLIENT_ID') CLIENT_SECRET = os.getenv('OAUTH_CLIENT_SECRET') TOKEN_URL = 'https://api.example.com/oauth/token' def get_oauth_token(): """Obtains an OAuth 2.0 access token using the Client Credentials flow.""" if not CLIENT_ID or not CLIENT_SECRET: raise ValueError("OAUTH_CLIENT_ID and OAUTH_CLIENT_SECRET must be set as environment variables.") headers = { 'Content-Type': 'application/x-www-form-urlencoded' } data = { 'grant_type': 'client_credentials', 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET } try: response = requests.post(TOKEN_URL, headers=headers, data=data) response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx) token_data = response.json() return token_data.get('access_token') except requests.exceptions.RequestException as e: print(f"Error obtaining token: {e}") return None def call_protected_api(api_url, access_token): """Calls a protected API endpoint with the obtained access token.""" if not access_token: print("No access token provided. Cannot call API.") return None headers = { 'Authorization': f'Bearer {access_token}', 'Accept': 'application/json' } try: response = requests.get(api_url, headers=headers) response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: print(f"Error calling protected API: {e}") return None # Example Usage: # if __name__ == '__main__': # token = get_oauth_token() # if token: # print(f"Access Token: {token[:10]}...") # data = call_protected_api('https://api.example.com/data', token) # if data: # print("API Response:", data)