Skip to content

Commit bb07223

Browse files
authored
Update api_client.py
1 parent aa24bff commit bb07223

File tree

1 file changed

+27
-28
lines changed

1 file changed

+27
-28
lines changed

api_client.py

Lines changed: 27 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,56 @@
1-
# api_client.py
2-
import requests
31
import json
2+
from datetime import datetime
43
import logging
5-
from datetime import datetime, timedelta
6-
from config import API_BASE_URL, TOKEN_ENDPOINT
4+
from config import APIConfig
75

86
class APIClient:
9-
def __init__(self, credentials):
10-
self.credentials = credentials
7+
def __init__(self):
8+
self.config = APIConfig
119
self.session = requests.Session()
10+
self.logger = logging.getLogger(__name__)
11+
logging.basicConfig(**self.config.LOGGING_CONFIG)
1212
self.token_info = self.load_token() or self.authenticate()
1313

1414
def authenticate(self):
15-
""" Authenticate with the API and return the token information. """
15+
""" Authenticates with the API and stores the new token information. """
16+
self.logger.info("Authenticating with API to retrieve new tokens.")
1617
data = {
1718
'grant_type': 'client_credentials',
18-
'client_id': self.credentials.app_key,
19-
'client_secret': self.credentials.app_secret
19+
'client_id': self.config.APP_KEY,
20+
'client_secret': self.config.APP_SECRET
2021
}
21-
response = self.session.post(TOKEN_ENDPOINT, data=data)
22-
response.raise_for_status() # This will raise an error for non-200 responses
22+
response = self.session.post(f"{self.config.API_BASE_URL}/v1/oauth/token", data=data)
23+
response.raise_for_status()
2324
token_data = response.json()
2425
self.save_token(token_data)
2526
return token_data
2627

2728
def save_token(self, token_data):
28-
""" Save token data to a local JSON file """
29+
""" Saves the token data securely to a file. """
30+
token_data['expires_at'] = (datetime.now() + timedelta(seconds=token_data['expires_in'])).isoformat()
2931
with open('token_data.json', 'w') as f:
3032
json.dump(token_data, f)
33+
self.logger.info("Token data saved successfully.")
3134

3235
def load_token(self):
33-
""" Load token data from a local JSON file """
36+
""" Loads the token data from a file if it is still valid. """
3437
try:
3538
with open('token_data.json', 'r') as f:
3639
token_data = json.load(f)
37-
token_expiration = datetime.fromisoformat(token_data['expires_at'])
38-
if datetime.now() < token_expiration - timedelta(minutes=5): # buffer for token expiration
40+
if datetime.now() < datetime.fromisoformat(token_data['expires_at']):
41+
self.logger.info("Token loaded successfully from file.")
3942
return token_data
40-
except (FileNotFoundError, KeyError):
41-
return None
43+
except (FileNotFoundError, KeyError, ValueError) as e:
44+
self.logger.warning(f"Loading token failed: {e}")
45+
return None
4246

4347
def make_request(self, method, endpoint, **kwargs):
44-
""" Make an HTTP request using the authenticated session. """
45-
url = f"{API_BASE_URL}{endpoint}"
48+
""" Makes an HTTP request using the authenticated session. """
49+
url = f"{self.config.API_BASE_URL}{endpoint}"
4650
response = self.session.request(method, url, **kwargs)
47-
if response.status_code == 401: # Token expired or not valid
51+
if response.status_code == 401: # Token expired
52+
self.logger.warning("Token expired. Refreshing token...")
4853
self.token_info = self.authenticate()
49-
response = self.session.request(method, url, **kwargs) # Retry request
50-
response.raise_for_status() # Raise an exception for bad responses
54+
response = self.session.request(method, url, **kwargs)
55+
response.raise_for_status()
5156
return response.json()
52-
53-
def get(self, endpoint, params=None):
54-
return self.make_request('GET', endpoint, params=params)
55-
56-
def post(self, endpoint, data=None):
57-
return self.make_request('POST', endpoint, json=data)

0 commit comments

Comments
 (0)