|
1 | 1 | # api_client.py |
2 | 2 | import requests |
3 | | -from .credentials import Credentials |
4 | | -from .tokens import TokenManager |
5 | | -from .api_utilities import ParameterParser |
6 | | -from .config import API_BASE_URL |
| 3 | +import json |
| 4 | +import logging |
| 5 | +from datetime import datetime, timedelta |
| 6 | +from config import API_BASE_URL, TOKEN_ENDPOINT |
7 | 7 |
|
8 | 8 | class APIClient: |
9 | | - def __init__(self): |
10 | | - self.base_url = API_BASE_URL |
| 9 | + def __init__(self, credentials): |
| 10 | + self.credentials = credentials |
11 | 11 | self.session = requests.Session() |
12 | | - self.setup_session() |
13 | | - |
14 | | - def setup_session(self): |
15 | | - """Prepare the session with necessary headers and auth setup.""" |
16 | | - token = TokenManager.get_access_token() |
17 | | - self.session.headers.update({ |
18 | | - 'Authorization': f'Bearer {token}', |
19 | | - 'Content-Type': 'application/json' |
20 | | - }) |
21 | | - |
22 | | - def make_request(self, method, endpoint, params=None, data=None): |
23 | | - """General method to make HTTP requests.""" |
24 | | - url = f"{self.base_url}{endpoint}" |
| 12 | + self.token_info = self.load_token() or self.authenticate() |
| 13 | + |
| 14 | + def authenticate(self): |
| 15 | + """ Authenticate with the API and return the token information. """ |
| 16 | + data = { |
| 17 | + 'grant_type': 'client_credentials', |
| 18 | + 'client_id': self.credentials.app_key, |
| 19 | + 'client_secret': self.credentials.app_secret |
| 20 | + } |
| 21 | + response = self.session.post(TOKEN_ENDPOINT, data=data) |
| 22 | + response.raise_for_status() # This will raise an error for non-200 responses |
| 23 | + token_data = response.json() |
| 24 | + self.save_token(token_data) |
| 25 | + return token_data |
| 26 | + |
| 27 | + def save_token(self, token_data): |
| 28 | + """ Save token data to a local JSON file """ |
| 29 | + with open('token_data.json', 'w') as f: |
| 30 | + json.dump(token_data, f) |
| 31 | + |
| 32 | + def load_token(self): |
| 33 | + """ Load token data from a local JSON file """ |
25 | 34 | try: |
26 | | - response = self.session.request(method, url, params=ParameterParser.clean_params(params), json=data) |
27 | | - response.raise_for_status() # Will raise an HTTPError for bad requests |
28 | | - return response.json() |
29 | | - except requests.RequestException as e: |
30 | | - return {'error': str(e)} |
31 | | - |
32 | | - def refresh_tokens(self): |
33 | | - """Handle token refresh logic.""" |
34 | | - new_tokens = TokenManager.refresh_tokens() |
35 | | - if new_tokens: |
36 | | - self.setup_session() # Update session with new tokens |
| 35 | + with open('token_data.json', 'r') as f: |
| 36 | + 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 |
| 39 | + return token_data |
| 40 | + except (FileNotFoundError, KeyError): |
| 41 | + return None |
| 42 | + |
| 43 | + def make_request(self, method, endpoint, **kwargs): |
| 44 | + """ Make an HTTP request using the authenticated session. """ |
| 45 | + url = f"{API_BASE_URL}{endpoint}" |
| 46 | + response = self.session.request(method, url, **kwargs) |
| 47 | + if response.status_code == 401: # Token expired or not valid |
| 48 | + 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 |
| 51 | + return response.json() |
37 | 52 |
|
38 | 53 | def get(self, endpoint, params=None): |
39 | | - """Wrapper for GET requests.""" |
40 | 54 | return self.make_request('GET', endpoint, params=params) |
41 | 55 |
|
42 | 56 | def post(self, endpoint, data=None): |
43 | | - """Wrapper for POST requests.""" |
44 | | - return self.make_request('POST', endpoint, data=data) |
45 | | - |
46 | | - def put(self, endpoint, data=None): |
47 | | - """Wrapper for PUT requests.""" |
48 | | - return self.make_request('PUT', endpoint, data=data) |
49 | | - |
50 | | - def delete(self, endpoint, params=None): |
51 | | - """Wrapper for DELETE requests.""" |
52 | | - return self.make_request('DELETE', endpoint, params=params) |
| 57 | + return self.make_request('POST', endpoint, json=data) |
0 commit comments