-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.py
84 lines (66 loc) · 2.64 KB
/
client.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
#!/usr/bin/env python3
# -*- coding: utf8 -*-
import logging
import requests
from .exceptions import HibobException
log = logging.getLogger('hibiob.client')
log.setLevel(logging.INFO)
class Client:
request_timeout = 30
url = "https://api.hibob.com/v1/"
def __init__(self, api_token):
self.api_token = api_token
@staticmethod
def parse_response(response):
if response.headers['Content-Type'] != 'application/json':
log.debug('Response is not application/json, returning raw response')
return response
try:
return response.json()
except ValueError:
log.debug('Could not convert response to json, returning raw response')
return response
def make_request(self, method, endpoint, json_body=None, query=None, body=None, files=None):
methods = {
'get': requests.get,
'post': requests.post,
'put': requests.put,
'delete': requests.delete
}
method = method.lower()
request = methods.get(method, requests.get)
request_params = {
'headers': {
'Accept': 'application/json',
"Authorization": self.api_token
},
'json': json_body,
'params': query,
'data': body,
'files': files,
'timeout': self.request_timeout
}
response = request(
self.url + endpoint,
**request_params
)
parsed_response = self.parse_response(response)
try:
response.raise_for_status()
except requests.HTTPError as error:
log.exception(error)
log.debug(response)
if isinstance(parsed_response, dict):
# response is json and was parsed to dict
raise HibobException(parsed_response.get('error'))
# fallback to requests exception
raise error
return parsed_response
def get(self, endpoint, query=None):
return self.make_request('get', endpoint, query=query)
def post(self, endpoint, json_body=None, query=None, body=None, files=None):
return self.make_request('post', endpoint, json_body=json_body, query=query, body=body, files=files)
def put(self, endpoint, json_body=None, query=None, body=None, files=None):
return self.make_request('post', endpoint, json_body=json_body, query=query, body=body, files=files)
def delete(self, endpoint, json_body=None, query=None, body=None, files=None):
return self.make_request('post', endpoint, json_body=json_body, query=query, body=body, files=files)