Created
December 23, 2015 00:44
-
-
Save dhhagan/90b020c8322902ff4887 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import requests | |
| import json | |
| class API(object): | |
| def __init__(self, **kwargs): | |
| self._key = kwargs.pop('key', '') | |
| self._pswd = kwargs.pop('pswd', '') | |
| self._version = kwargs.pop('version', None) | |
| self._baseurl = kwargs.pop('baseurl', None) | |
| self._headers = {'content-type': 'application/json'} | |
| def _make_url(self, endpoint, **kwargs): | |
| endpoint = "{}/{}/{}".format(self._baseurl, self._version, endpoint) | |
| extra = [] | |
| for key, value in kwargs.items(): | |
| if isinstance(value, list): | |
| value = ','.join(value) | |
| extra.append("{}={}".format(key, value)) | |
| if len(extra) > 0: | |
| endpoint = '?'.join([endpoint, '&'.join(extra)]) | |
| return endpoint | |
| def _send(self, endpoint, method = 'GET', data = None, **kwargs): | |
| ''' ''' | |
| auth = (self._key, self._pswd) | |
| url = self._make_url(endpoint, **kwargs) | |
| if data: | |
| data = json.dumps(data) | |
| if method == 'GET': | |
| try: | |
| resp = requests.get(url, auth = auth, headers = self._headers) | |
| except Exception as error: | |
| raise ApiError(error) | |
| elif method == 'POST': | |
| try: | |
| resp = requests.post(url, auth = auth, headers = self._headers, data = data) | |
| except Exception as error: | |
| raise ApiError(error) | |
| elif method == 'PUT': | |
| try: | |
| resp = requests.put(url, auth = auth, headers = self._headers, data = data) | |
| except Exception as error: | |
| raise ApiError(error) | |
| elif method == 'DELETE': | |
| try: | |
| resp = requests.delete(url, auth = auth, headers = self._headers) | |
| except Exception as error: | |
| raise ApiError(error) | |
| else: | |
| return "Invalid Method" | |
| return resp.status_code, resp.json() | |
| def _get(self, url, **kwargs): | |
| return self._send(url, 'GET', **kwargs) | |
| def _post(self, url, data): | |
| pass | |
| def _put(self, url, data): | |
| pass | |
| def _delete(self, url): | |
| pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment