This repository was archived by the owner on Jul 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathclient.py
More file actions
46 lines (37 loc) · 1.6 KB
/
client.py
File metadata and controls
46 lines (37 loc) · 1.6 KB
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
import json
import requests
import typing
from .constants import API_BASE_URL
from .utils import buildUrlWithParams, mergeDict
class Client(object):
"""TypeForm API HTTP client"""
def __init__(self, token: str, headers: dict = {}):
"""Constructor for TypeForm API client"""
self.__headers = mergeDict({
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'bearer %s' % token
}, headers)
def request(self, method: str, url: str, data: any = {}, params: dict = {}, headers={}) -> typing.Union[str, dict]:
requestUrl = buildUrlWithParams((API_BASE_URL + url), params)
requestHeaders = mergeDict(self.__headers, headers)
requestData = ''
if type(data) is dict:
requestData = json.dumps(data) if len(data.keys()) > 0 else ''
if type(data) is list:
requestData = json.dumps(data) if len(data) > 0 else ''
result = requests.request(method, requestUrl, data=requestData, headers=requestHeaders)
return self.__validator(result)
def __validator(self, result: requests.Response) -> typing.Union[str, dict]:
try:
body = json.loads(result.text)
except Exception:
body = {}
if type(body) is dict and body.get('code', None) is not None:
raise Exception(body.get('description'))
elif result.status_code >= 400:
raise Exception(' '.join([str(result.status_code),result.reason]))
elif len(result.text) == 0:
return 'OK'
else:
return body