-
Notifications
You must be signed in to change notification settings - Fork 7
/
api.py
344 lines (293 loc) · 12.9 KB
/
api.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import logging
import json
import base64
from typing import Union
import httpx
from httpx import ConnectError
import asyncio
from .model import RequestsMethods, ERROR_MESSAGES, APIModel
class Api:
"""The class includes all necessary methods to make API calls to the Grafana API endpoints
Args:
grafana_api_model (APIModel): Inject a Grafana API model object that includes all necessary values and information
Attributes:
grafana_api_model (APIModel): This is where we store the grafana_api_model
"""
def __init__(self, grafana_api_model: APIModel):
self.grafana_api_model = grafana_api_model
def call_the_api(
self,
api_call: str,
method: RequestsMethods = RequestsMethods.GET,
json_complete: str = None,
org_id_header: int = None,
disable_provenance_header: bool = False,
response_status_code: bool = False,
) -> any:
"""The method execute a defined API call against the Grafana endpoints
Args:
api_call (str): Specify the API call endpoint
method (RequestsMethods): Specify the used method (default GET)
json_complete (str): Specify the inserted JSON as string
org_id_header (int): Specify the optional organization id as header for the corresponding API call
disable_provenance_header (bool): Specify the optional disable provenance as header for the corresponding API call (default False)
response_status_code (bool): Specify if the response should include the original status code (default False)
Raises:
Exception: Unspecified error by executing the API call
Returns:
api_call (any): Returns the value of the api call
"""
api_url: str = f"{self.grafana_api_model.host}{api_call}"
headers: dict = dict(
{"Authorization": f"Bearer {self.grafana_api_model.token}"},
)
if (
self.grafana_api_model.username is not None
and self.grafana_api_model.password is not None
):
credentials: str = base64.b64encode(
str.encode(
f"{self.grafana_api_model.username}:{self.grafana_api_model.password}"
)
).decode("utf-8")
headers.update({"Authorization": f"Basic {credentials}"})
headers["Content-Type"] = "application/json"
headers["Accept"] = "application/json"
if org_id_header is not None and isinstance(org_id_header, int):
headers["X-Grafana-Org-Id"] = org_id_header
if isinstance(disable_provenance_header, bool) and disable_provenance_header:
headers["X-Disable-Provenance"] = f"{disable_provenance_header}"
http: Union[httpx.Client, httpx.AsyncClient] = self.create_the_http_api_client(
headers
)
if self.grafana_api_model.http2_support:
async def _execute_async_api_call():
async with http:
return await self._execute_the_async_api_call(
http, method, api_url, response_status_code, json_complete
)
return asyncio.run(_execute_async_api_call())
return self._execute_the_api_call(
http, method, api_url, response_status_code, json_complete
)
def _execute_the_api_call(
self,
http: httpx.Client,
method: RequestsMethods,
api_url: str,
response_status_code: bool,
json_complete: str,
) -> any:
"""The method includes a functionality to execute a synchronous api call
Args:
http (httpx.Client): Specify the used synchronous client
method (RequestsMethods): Specify the used method
api_url (str): Specify the used api url
response_status_code (bool): Specify if the response code should be returned
json_complete (str): Specify the forwarded json in case of patch, post or put calls
Raises:
Exception: Unspecified error by executing the API call
Returns:
api_call (any): Returns the value of the api call
"""
try:
if method.value == RequestsMethods.GET.value:
return self._check_the_api_call_response(
http.request("GET", api_url),
response_status_code,
)
elif method.value == RequestsMethods.PUT.value:
if json_complete is not None:
return self._check_the_api_call_response(
http.request("PUT", api_url, content=json_complete),
response_status_code,
)
else:
logging.error("Please define the json_complete.")
raise Exception
elif method.value == RequestsMethods.POST.value:
if json_complete is not None:
return self._check_the_api_call_response(
http.request("POST", api_url, content=json_complete),
response_status_code,
)
else:
logging.error("Please define the json_complete.")
raise Exception
elif method.value == RequestsMethods.PATCH.value:
if json_complete is not None:
return self._check_the_api_call_response(
http.request("PATCH", api_url, content=json_complete),
response_status_code,
)
else:
logging.error("Please define the json_complete.")
raise Exception
elif method.value == RequestsMethods.DELETE.value:
return self._check_the_api_call_response(
http.request("DELETE", api_url), response_status_code
)
else:
logging.error("Please define a valid method.")
raise Exception
except Exception as e:
raise e
async def _execute_the_async_api_call(
self,
http: httpx.AsyncClient,
method: RequestsMethods,
api_url: str,
response_status_code: bool,
json_complete: str,
):
"""The method includes a functionality to execute an asynchronous api call
Args:
http (httpx.AsyncClient): Specify the used asynchronous client
method (RequestsMethods): Specify the used method
api_url (str): Specify the used api url
response_status_code (bool): Specify if the response code should be returned
json_complete (str): Specify the forwarded json in case of patch, post or put calls
Raises:
Exception: Unspecified error by executing the API call
Returns:
api_call (any): Returns the value of the api call
"""
try:
if method.value == RequestsMethods.GET.value:
return self._check_the_api_call_response(
await http.request("GET", api_url),
response_status_code,
)
elif method.value == RequestsMethods.PUT.value:
if json_complete is not None:
return self._check_the_api_call_response(
await http.request("PUT", api_url, content=json_complete),
response_status_code,
)
else:
logging.error("Please define the json_complete.")
raise Exception
elif method.value == RequestsMethods.POST.value:
if json_complete is not None:
return self._check_the_api_call_response(
await http.request("POST", api_url, content=json_complete),
response_status_code,
)
else:
logging.error("Please define the json_complete.")
raise Exception
elif method.value == RequestsMethods.PATCH.value:
if json_complete is not None:
return self._check_the_api_call_response(
await http.request("PATCH", api_url, content=json_complete),
response_status_code,
)
else:
logging.error("Please define the json_complete.")
raise Exception
elif method.value == RequestsMethods.DELETE.value:
return self._check_the_api_call_response(
await http.request("DELETE", api_url), response_status_code
)
else:
logging.error("Please define a valid method.")
raise Exception
except Exception as e:
raise e
@staticmethod
def _check_the_api_call_response(
response: any = None, response_status_code: bool = False
) -> any:
"""The method includes a functionality to check the output of API call method for errors
Args:
response (any): Specify the inserted response
response_status_code (bool): Specify if the original status code should be attached to the result (default False)
Raises:
Exception: Unspecified error by executing the API call
Returns:
api_call (any): Returns the value of the api call
"""
if Api._check_if_valid_json(response.text) and response.text != "null":
if (
len(json.loads(response.text)) != 0
and type(json.loads(response.text)) == dict
):
if (
"message" in json.loads(response.text).keys()
and json.loads(response.text)["message"] in ERROR_MESSAGES
):
logging.error(json.loads(response.text)["message"])
raise ConnectError(str(json.loads(response.text)["message"]))
json_response: Union[dict, list] = json.loads(response.text)
if isinstance(json_response, dict) and response_status_code:
json_response.update({"status": response.status_code})
elif isinstance(json_response, list) and response_status_code:
json_response[0].update({"status": response.status_code})
return json_response
else:
if response_status_code:
return dict({"status": response.status_code, "data": response.text})
else:
return response
@staticmethod
def _check_if_valid_json(response: any) -> bool:
"""The method includes a functionality to check if the response json is valid
Args:
response (any): Specify the inserted response json
Returns:
result (bool): Returns if the json is valid or not
"""
try:
json.loads(response)
except (TypeError, ValueError):
return False
return True
@staticmethod
def prepare_api_string(query_string: str) -> str:
"""The method includes a functionality to prepare the api string for the queries
Args:
query_string (str): Specify the corresponding query string
Returns:
query_string (str): Returns the adjusted query string
"""
if len(query_string) >= 1:
return f"{query_string}&"
else:
return query_string
def create_the_http_api_client(
self, headers: dict = None
) -> Union[httpx.Client, httpx.AsyncClient]:
"""The method includes a functionality to create the corresponding HTTP client
Args:
headers (dict): Specify the optional inserted headers (Default None)
Returns:
client (Union[httpx.Client, httpx.AsyncClient]): Returns the corresponding client
"""
transport: httpx.HTTPTransport = httpx.HTTPTransport(
verify=self.grafana_api_model.ssl_context,
retries=self.grafana_api_model.retries,
)
limits: httpx.Limits = httpx.Limits(
max_connections=self.grafana_api_model.num_pools
)
http2: bool = self.grafana_api_model.http2_support
if http2:
async_transport: httpx.AsyncHTTPTransport = httpx.AsyncHTTPTransport(
retries=self.grafana_api_model.retries, http2=http2
)
return httpx.AsyncClient(
http2=True,
limits=limits,
timeout=self.grafana_api_model.timeout,
headers=headers,
transport=async_transport,
verify=self.grafana_api_model.ssl_context,
)
else:
return httpx.Client(
limits=limits,
timeout=self.grafana_api_model.timeout,
headers=headers,
transport=transport,
verify=self.grafana_api_model.ssl_context,
)