|
| 1 | +import os |
| 2 | +import requests |
| 3 | +from .errors import DemandAPIError |
| 4 | + |
| 5 | + |
| 6 | +class DemandAPI(object): |
| 7 | + def __init__(self): |
| 8 | + self.client_id = os.getenv('DYNATA_DEMAND_CLIENT_ID', None) |
| 9 | + self.username = os.getenv('DYNATA_DEMAND_USERNAME', None) |
| 10 | + self.password = os.getenv('DYNATA_DEMAND_PASSWORD', None) |
| 11 | + if None in [self.client_id, self.username, self.password]: |
| 12 | + raise DemandAPIError("All authentication data is required.") |
| 13 | + self._access_token = None |
| 14 | + self.base_host = os.getenv('DYNATA_DEMAND_BASE_URL', 'https://api.researchnow.com') |
| 15 | + self.auth_base_url = '{}/auth/v1'.format(self.base_host) |
| 16 | + self.base_url = '{}/sample/v1'.format(self.base_host) |
| 17 | + |
| 18 | + def _check_authentication(self): |
| 19 | + if self._access_token is None: |
| 20 | + raise DemandAPIError('The API instance must be authenticated before calling this method.') |
| 21 | + |
| 22 | + def authenticate(self): |
| 23 | + url = '{}/token/password'.format(self.auth_base_url) |
| 24 | + payload = { |
| 25 | + 'clientId': self.client_id, |
| 26 | + 'password': self.password, |
| 27 | + 'username': self.username, |
| 28 | + } |
| 29 | + auth_response = requests.post(url, json=payload) |
| 30 | + if auth_response.status_code > 399: |
| 31 | + raise DemandAPIError('Authentication failed with status {} and error: {}'.format( |
| 32 | + auth_response.status_code, |
| 33 | + auth_response.json()) |
| 34 | + ) |
| 35 | + self._access_token = auth_response.json().get('accessToken') |
| 36 | + return self._access_token |
| 37 | + |
| 38 | + def api_call(self, uri, method, payload): |
| 39 | + self._check_authentication() |
| 40 | + url = '{}{}'.format(self.base_url, uri) |
| 41 | + response = requests.request(url=url, method=method, json=payload, headers={'oauth_access_token': self._access_token}) |
| 42 | + if response.status_code > 399: |
| 43 | + raise DemandAPIError('Demand API request failed with status {}. Response: {}'.format(response.status_code, response.json())) |
| 44 | + return response.json() |
0 commit comments