from requests_oauthlib import OAuth2Session from oauthlib.oauth2 import BackendApplicationClient from dotenv import load_dotenv import os environment_name = os.getenv('ENV_NAME', 'qa') # need to find a place for this dotenv_path = f'.env.{environment_name}' load_dotenv(dotenv_path) client_id = os.getenv('CLIENT_ID') client_secret = os.getenv('CLIENT_SECRET') token_url = os.getenv('TOKEN_URL') username = os.getenv('USERNAME') password = os.getenv('PASSWORD') audience = os.getenv('AUDIENCE') scope = os.getenv('SCOPE', '').split(',') api_url = os.getenv('API_URL') def get_token(client_id, client_secret, token_url, username, password, audience, scope): client = BackendApplicationClient(client_id=client_id) oauth = OAuth2Session(client=client) token = oauth.fetch_token( token_url=token_url, username=username, password=password, client_id=client_id, client_secret=client_secret, audience=audience, scope=scope ) return token def api_client(resource_url, auth_token): client = OAuth2Session(token=auth_token) response = client.get(resource_url) return response.content # Fetch token token = get_token(client_id, client_secret, token_url, username, password, audience, scope) # Now we can make API calls api_response = api_client(api_url + '/resource', token) print(api_response)