|
1 | | -# api_client.py |
2 | | -import requests |
3 | 1 | import json |
| 2 | +from datetime import datetime |
4 | 3 | import logging |
5 | | -from datetime import datetime, timedelta |
6 | | -from config import API_BASE_URL, TOKEN_ENDPOINT |
| 4 | +from config import APIConfig |
7 | 5 |
|
8 | 6 | class APIClient: |
9 | | - def __init__(self, credentials): |
10 | | - self.credentials = credentials |
| 7 | + def __init__(self): |
| 8 | + self.config = APIConfig |
11 | 9 | self.session = requests.Session() |
| 10 | + self.logger = logging.getLogger(__name__) |
| 11 | + logging.basicConfig(**self.config.LOGGING_CONFIG) |
12 | 12 | self.token_info = self.load_token() or self.authenticate() |
13 | 13 |
|
14 | 14 | 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.") |
16 | 17 | data = { |
17 | 18 | '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 |
20 | 21 | } |
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() |
23 | 24 | token_data = response.json() |
24 | 25 | self.save_token(token_data) |
25 | 26 | return token_data |
26 | 27 |
|
27 | 28 | 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() |
29 | 31 | with open('token_data.json', 'w') as f: |
30 | 32 | json.dump(token_data, f) |
| 33 | + self.logger.info("Token data saved successfully.") |
31 | 34 |
|
32 | 35 | 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. """ |
34 | 37 | try: |
35 | 38 | with open('token_data.json', 'r') as f: |
36 | 39 | 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.") |
39 | 42 | 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 |
42 | 46 |
|
43 | 47 | 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}" |
46 | 50 | 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...") |
48 | 53 | 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() |
51 | 56 | 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