import os import requests class PingApi(): def __init__(self): self.url = os.getenv('API_URL') self.auth_url = os.getenv('AUTH_URL') client_id = os.getenv('CLIENT_ID') client_secret = os.getenv('CLIENT_SECRET') self.auth_payload = f'grant_type=client_credentials&client_id={client_id}&client_secret={client_secret}&scope=categorization' self.access_token = self.authorize() def authorize(self): headers = {'Content-Type': 'application/x-www-form-urlencoded'} response = requests.request("POST", self.auth_url, headers=headers, data=self.auth_payload) try: access_token = response.json()['access_token'] except Exception as e: print(response.text) raise e return access_token def ping_api(self, f_path, endpoint): payload = {} headers = { 'Authorization': f"Bearer {self.access_token}" } files = [('file', (os.path.basename(f_path), open(f_path, 'rb'), 'image/jpeg'))] response = requests.request("POST", self.url + '/' + endpoint, headers=headers, data=payload, files=files) try: rsp_json = response.json() except Exception as e: print(response.text) raise e return rsp_json