-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathWaApi.py
259 lines (207 loc) · 9.52 KB
/
WaApi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
r"""
This module provides set of classes for working with WildApricot public API v2.
Public API documentation can be found here: http://help.wildapricot.com/display/DOC/API+Version+2
Example:
api = WaApi.WaApiClient()
api.authenticate_with_contact_credentials("[email protected]", "your_password")
accounts = api.execute_request("/v2/accounts")
for account in accounts:
print(account.PrimaryDomainName)
"""
__author__ = '[email protected]'
import datetime
import urllib.request
import urllib.response
import urllib.error
import urllib.parse
import json
import base64
from pprint import pprint
class WaApiClient(object):
"""Wild apricot API client."""
auth_endpoint = "https://oauth.wildapricot.org/auth/token"
api_endpoint = "https://api.wildapricot.org"
_token = None
client_id = None
client_secret = None
def __init__(self, client_id, client_secret):
self.client_id = client_id
self.client_secret = client_secret
def authenticate_with_apikey(self, api_key, scope=None):
"""perform authentication by api key and store result for execute_request method
api_key -- secret api key from account settings
scope -- optional scope of authentication request. If None full list of API scopes will be used.
"""
scope = "auto" if scope is None else scope
data = {
"grant_type": "client_credentials",
"scope": scope,
"obtain_refresh_token": "true"
}
encoded_data = urllib.parse.urlencode(data).encode()
request = urllib.request.Request(self.auth_endpoint, encoded_data, method="POST")
request.add_header("ContentType", "application/x-www-form-urlencoded")
request.add_header("Authorization", 'Basic ' + base64.standard_b64encode(('APIKEY:' + api_key).encode()).decode())
pprint('---authenticate_with_apikey()---')
pprint(vars(request))
pprint('----------------------')
response = urllib.request.urlopen(request)
self._token = WaApiClient._parse_response(response)
self._token.retrieved_at = datetime.datetime.now()
def authenticate_with_contact_credentials(self, username, password, scope=None):
"""perform authentication by contact credentials and store result for execute_request method
username -- typically a contact email
password -- contact password
scope -- optional scope of authentication request. If None full list of API scopes will be used.
"""
scope = "auto" if scope is None else scope
data = {
"grant_type": "password",
"username": username,
"password": password,
"scope": scope
}
encoded_data = urllib.parse.urlencode(data).encode()
request = urllib.request.Request(self.auth_endpoint, encoded_data, method="POST")
request.add_header("ContentType", "application/x-www-form-urlencoded")
auth_header = base64.standard_b64encode((self.client_id + ':' + self.client_secret).encode()).decode()
request.add_header("Authorization", 'Basic ' + auth_header)
response = urllib.request.urlopen(request)
self._token = WaApiClient._parse_response(response)
self._token.retrieved_at = datetime.datetime.now()
def execute_request_raw(self, api_url, api_request_object=None, method=None, data=None):
"""
perform api request and return result as an instance of ApiObject or list of ApiObjects
api_url -- absolute or relative api resource url
api_request_object -- any json serializable object to send to API
method -- HTTP method of api request. Default: GET if api_request_object is None else POST
"""
if self._token is None:
raise ApiException("Access token was is not obtained. "
"Call authenticate_with_apikey or authenticate_with_contact_credentials first.")
if not api_url.startswith("http"):
api_url = self.api_endpoint + api_url
if method is None:
if api_request_object is None:
method = "GET"
else:
method = "POST"
data_as_bytes = bytes(json.dumps(data),encoding='utf-8')
request = urllib.request.Request(api_url, method=method,data=data_as_bytes)
if api_request_object is not None:
request.data = json.dumps(api_request_object, cls=_ApiObjectEncoder).encode()
request.add_header("Content-Type", "application/json")
request.add_header("Accept", "application/json")
request.add_header("Authorization", "Bearer " + self._get_access_token())
pprint('execute_request_raw() request ----------------')
pprint(request.__dict__)
if (data is not None):
pprint('execute_request_raw() data -----------------')
#pprint(json.dumps(data))
pprint((data))
pprint('-----------------')
try:
response = urllib.request.urlopen(request)
return response
except urllib.error.HTTPError as httpErr:
if httpErr.code == 400:
raise ApiException(httpErr.read())
else:
raise
def execute_request(self, api_url, api_request_object=None, method=None):
"""
perform api request and return result as an instance of ApiObject or list of ApiObjects
api_url -- absolute or relative api resource url
api_request_object -- any json serializable object to send to API
method -- HTTP method of api request. Default: GET if api_request_object is None else POST
"""
if self._token is None:
raise ApiException("Access token was is not obtained. "
"Call authenticate_with_apikey or authenticate_with_contact_credentials first.")
if not api_url.startswith("http"):
api_url = self.api_endpoint + api_url
if method is None:
if api_request_object is None:
method = "GET"
else:
method = "POST"
request = urllib.request.Request(api_url, method=method)
if api_request_object is not None:
request.data = json.dumps(api_request_object, cls=_ApiObjectEncoder).encode()
request.add_header("Content-Type", "application/json")
request.add_header("Accept", "application/json")
request.add_header("Authorization", "Bearer " + self._get_access_token())
pprint('execute_request() request ----------------')
pprint(request.__dict__)
pprint('-----------------')
try:
response = urllib.request.urlopen(request)
return WaApiClient._parse_response(response)
except urllib.error.HTTPError as httpErr:
if httpErr.code == 400:
raise ApiException(httpErr.read())
else:
raise
def _get_access_token(self):
expires_at = self._token.retrieved_at + datetime.timedelta(seconds=self._token.expires_in - 100)
if datetime.datetime.utcnow() > expires_at:
self._refresh_auth_token()
return self._token.access_token
def _refresh_auth_token(self):
data = {
"grant_type": "refresh_token",
"refresh_token": self._token.refresh_token
}
encoded_data = urllib.parse.urlencode(data).encode()
request = urllib.request.Request(self.auth_endpoint, encoded_data, method="POST")
request.add_header("ContentType", "application/x-www-form-urlencoded")
auth_header = base64.standard_b64encode((self.client_id + ':' + self.client_secret).encode()).decode()
request.add_header("Authorization", 'Basic ' + auth_header)
response = urllib.request.urlopen(request)
self._token = WaApiClient._parse_response(response)
self._token.retrieved_at = datetime.datetime.now()
@staticmethod
def _parse_response(http_response):
decoded = json.loads(http_response.read().decode())
pprint('_parse_response()------------------')
pprint(decoded)
pprint('------------------')
if isinstance(decoded, list):
result = []
for item in decoded:
result.append(ApiObject(item))
return result
elif isinstance(decoded, dict):
return ApiObject(decoded)
else:
return None
class ApiException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class ApiObject(object):
"""Represent any api call input or output object"""
def __init__(self, state):
self.__dict__ = state
for key, value in vars(self).items():
if isinstance(value, dict):
self.__dict__[key] = ApiObject(value)
elif isinstance(value, list):
new_list = []
for list_item in value:
if isinstance(list_item, dict):
new_list.append(ApiObject(list_item))
else:
new_list.append(list_item)
self.__dict__[key] = new_list
def __str__(self):
return json.dumps(self.__dict__)
def __repr__(self):
return json.dumps(self.__dict__)
class _ApiObjectEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, ApiObject):
return obj.__dict__
# Let the base class default method raise the TypeError
return json.JSONEncoder.default(self, obj)