-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_client.py
More file actions
172 lines (152 loc) · 5.42 KB
/
Copy pathapi_client.py
File metadata and controls
172 lines (152 loc) · 5.42 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
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
import logging
from typing import Any, Mapping, Optional
from requests import RequestException, Response, Session
from requests.adapters import HTTPAdapter
from urllib3 import Retry
logger = logging.getLogger("ms_python_client")
_Headers = Mapping[str, str]
_Data = Mapping[str, Any]
class ApiClient:
def __init__(self, api_base_url: str):
self.api_base_url = api_base_url
self.timeout = 10
self.session = Session()
retry_strategy = Retry(
total=3,
backoff_factor=1,
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["HEAD", "GET", "PUT", "DELETE", "OPTIONS"],
)
adapter = HTTPAdapter(max_retries=retry_strategy)
self.session.mount("http://", adapter)
self.session.mount("https://", adapter)
def build_headers(self, extra_headers: Optional[_Headers] = None) -> dict:
"""Create the headers for a request appending the ones in the params
Args:
extra_headers (dict): Mapping of headers that will be appended to the default ones
Returns:
dict: All the headers
"""
headers: dict[str, str] = {}
if extra_headers:
headers.update(extra_headers)
return headers
def make_get_request(self, api_path: str, headers: _Headers) -> Response:
"""Makes a GET request using requests
Args:
api_path (str): The URL path
headers (dict): The headers of the request
Returns:
Response: The response of the request
"""
response = None
full_url = self.api_base_url + api_path
logger.info("GET %s", api_path)
try:
response = self.session.get(full_url, headers=headers, timeout=self.timeout)
response.raise_for_status()
except RequestException as e:
logger.error(e)
if isinstance(response, Response) and response.text:
logger.error(response.text)
raise e
logger.debug(
"GET [%s] - %d in %fs",
api_path,
response.status_code,
response.elapsed.total_seconds(),
)
return response
def make_post_request(
self, api_path: str, headers: _Headers, json: Optional[_Data] = None
) -> Response:
"""Makes a POST request using requests
Args:
api_path (str): The URL path
headers (dict): The headers of the request
json (dict): The body of the request
Returns:
Response: The response of the request
"""
response = None
full_url = self.api_base_url + api_path
logger.info("POST %s", api_path)
try:
response = self.session.post(
full_url, headers=headers, json=json, timeout=self.timeout
)
response.raise_for_status()
except RequestException as e:
logger.error(e)
if isinstance(response, Response) and response.text:
logger.error(response.text)
raise e
logger.debug(
"POST [%s] - %d in %fs",
api_path,
response.status_code,
response.elapsed.total_seconds(),
)
return response
def make_patch_request(
self, api_path: str, headers: _Headers, json: Optional[_Data] = None
) -> Response:
"""Makes a PATCH request using requests
Args:
api_path (str): The URL path
headers (dict): The headers of the request
json (dict): The body of the request
Returns:
Response: The response of the request
"""
response = None
full_url = self.api_base_url + api_path
logger.info("PATCH %s", api_path)
try:
response = self.session.patch(
full_url, headers=headers, json=json, timeout=self.timeout
)
response.raise_for_status()
except RequestException as e:
logger.error(e)
if isinstance(response, Response) and response.text:
logger.error(response.text)
raise e
logger.debug(
"PATCH [%s] - %d in %fs",
api_path,
response.status_code,
response.elapsed.total_seconds(),
)
return response
def make_delete_request(
self, api_path: str, headers: _Headers, json: Optional[_Data] = None
) -> Response:
"""Makes a DELETE request using requests
Args:
api_path (str): The URL path
headers (dict): The headers of the request
json (dict): The body of the request
Returns:
Response: The response of the request
"""
response = None
full_url = self.api_base_url + api_path
logger.info("DELETE %s", api_path)
try:
response = self.session.delete(
full_url, headers=headers, json=json, timeout=self.timeout
)
response.raise_for_status()
except RequestException as e:
logger.error(e)
if isinstance(response, Response) and response.text:
logger.error(response.text)
raise e
logger.debug(
"DELETE [%s] - %d in %fs",
api_path,
response.status_code,
response.elapsed.total_seconds(),
)
return response