stackit-objectstorage 0.0.1a0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. stackit/objectstorage/__init__.py +73 -0
  2. stackit/objectstorage/api/__init__.py +4 -0
  3. stackit/objectstorage/api/default_api.py +3349 -0
  4. stackit/objectstorage/api_client.py +626 -0
  5. stackit/objectstorage/api_response.py +23 -0
  6. stackit/objectstorage/configuration.py +111 -0
  7. stackit/objectstorage/exceptions.py +198 -0
  8. stackit/objectstorage/models/__init__.py +54 -0
  9. stackit/objectstorage/models/access_key.py +87 -0
  10. stackit/objectstorage/models/bucket.py +93 -0
  11. stackit/objectstorage/models/create_access_key_payload.py +82 -0
  12. stackit/objectstorage/models/create_access_key_response.py +97 -0
  13. stackit/objectstorage/models/create_bucket_response.py +82 -0
  14. stackit/objectstorage/models/create_credentials_group_payload.py +83 -0
  15. stackit/objectstorage/models/create_credentials_group_response.py +96 -0
  16. stackit/objectstorage/models/credentials_group.py +89 -0
  17. stackit/objectstorage/models/delete_access_key_response.py +84 -0
  18. stackit/objectstorage/models/delete_bucket_response.py +82 -0
  19. stackit/objectstorage/models/delete_credentials_group_response.py +82 -0
  20. stackit/objectstorage/models/detailed_error.py +82 -0
  21. stackit/objectstorage/models/error_message.py +98 -0
  22. stackit/objectstorage/models/get_bucket_response.py +92 -0
  23. stackit/objectstorage/models/http_validation_error.py +98 -0
  24. stackit/objectstorage/models/list_access_keys_response.py +100 -0
  25. stackit/objectstorage/models/list_buckets_response.py +98 -0
  26. stackit/objectstorage/models/list_credentials_groups_response.py +100 -0
  27. stackit/objectstorage/models/location_inner.py +147 -0
  28. stackit/objectstorage/models/project_scope.py +36 -0
  29. stackit/objectstorage/models/project_status.py +84 -0
  30. stackit/objectstorage/models/validation_error.py +98 -0
  31. stackit/objectstorage/py.typed +0 -0
  32. stackit/objectstorage/rest.py +148 -0
  33. stackit_objectstorage-0.0.1a0.dist-info/METADATA +45 -0
  34. stackit_objectstorage-0.0.1a0.dist-info/RECORD +35 -0
  35. stackit_objectstorage-0.0.1a0.dist-info/WHEEL +4 -0
@@ -0,0 +1,626 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ STACKIT Object Storage API
5
+
6
+ STACKIT API to manage the Object Storage
7
+
8
+ The version of the OpenAPI document: 1.0.9
9
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
10
+
11
+ Do not edit the class manually.
12
+ """ # noqa: E501 docstring might be too long
13
+
14
+ import datetime
15
+ import json
16
+ import mimetypes
17
+ import os
18
+ import re
19
+ import tempfile
20
+ from enum import Enum
21
+ from typing import Dict, List, Optional, Tuple, Union
22
+ from urllib.parse import quote
23
+
24
+ from dateutil.parser import parse
25
+ from pydantic import SecretStr
26
+ from stackit.core.configuration import Configuration
27
+
28
+ import stackit.objectstorage.models
29
+ from stackit.objectstorage import rest
30
+ from stackit.objectstorage.api_response import ApiResponse
31
+ from stackit.objectstorage.api_response import T as ApiResponseT
32
+ from stackit.objectstorage.configuration import HostConfiguration
33
+ from stackit.objectstorage.exceptions import (
34
+ ApiException,
35
+ )
36
+
37
+
38
+ RequestSerialized = Tuple[str, str, Dict[str, str], Optional[str], List[str]]
39
+
40
+
41
+ class ApiClient:
42
+ """Generic API client for OpenAPI client library builds.
43
+
44
+ OpenAPI generic API client. This client handles the client-
45
+ server communication, and is invariant across implementations. Specifics of
46
+ the methods and models for each application are generated from the OpenAPI
47
+ templates.
48
+
49
+ :param configuration: .Configuration object for this client
50
+ :param header_name: a header to pass when making calls to the API.
51
+ :param header_value: a header value to pass when making calls to
52
+ the API.
53
+ :param cookie: a cookie to include in the header when making calls
54
+ to the API
55
+ """
56
+
57
+ PRIMITIVE_TYPES = (float, bool, bytes, str, int)
58
+ NATIVE_TYPES_MAPPING = {
59
+ "int": int,
60
+ "long": int, # TODO remove as only py3 is supported?
61
+ "float": float,
62
+ "str": str,
63
+ "bool": bool,
64
+ "date": datetime.date,
65
+ "datetime": datetime.datetime,
66
+ "object": object,
67
+ }
68
+
69
+ def __init__(self, configuration, header_name=None, header_value=None, cookie=None) -> None:
70
+ self.config: Configuration = configuration
71
+
72
+ if self.config.custom_endpoint is None:
73
+ host_config = HostConfiguration(region=self.config.region, server_index=self.config.server_index)
74
+ self.host = host_config.host
75
+ else:
76
+ self.host = self.config.custom_endpoint
77
+
78
+ self.rest_client = rest.RESTClientObject(self.config)
79
+ self.default_headers = {}
80
+ if header_name is not None:
81
+ self.default_headers[header_name] = header_value
82
+ self.cookie = cookie
83
+ # Set default User-Agent.
84
+ self.user_agent = "OpenAPI-Generator/1.0.0/python"
85
+
86
+ def __enter__(self):
87
+ return self
88
+
89
+ def __exit__(self, exc_type, exc_value, traceback):
90
+ pass
91
+
92
+ @property
93
+ def user_agent(self):
94
+ """User agent for this API client"""
95
+ return self.default_headers["User-Agent"]
96
+
97
+ @user_agent.setter
98
+ def user_agent(self, value):
99
+ self.default_headers["User-Agent"] = value
100
+
101
+ def set_default_header(self, header_name, header_value):
102
+ self.default_headers[header_name] = header_value
103
+
104
+ _default = None
105
+
106
+ @classmethod
107
+ def get_default(cls):
108
+ """Return new instance of ApiClient.
109
+
110
+ This method returns newly created, based on default constructor,
111
+ object of ApiClient class or returns a copy of default
112
+ ApiClient.
113
+
114
+ :return: The ApiClient object.
115
+ """
116
+ if cls._default is None:
117
+ cls._default = ApiClient()
118
+ return cls._default
119
+
120
+ @classmethod
121
+ def set_default(cls, default):
122
+ """Set default instance of ApiClient.
123
+
124
+ It stores default ApiClient.
125
+
126
+ :param default: object of ApiClient.
127
+ """
128
+ cls._default = default
129
+
130
+ def param_serialize(
131
+ self,
132
+ method,
133
+ resource_path,
134
+ path_params=None,
135
+ query_params=None,
136
+ header_params=None,
137
+ body=None,
138
+ post_params=None,
139
+ files=None,
140
+ auth_settings=None,
141
+ collection_formats=None,
142
+ _host=None,
143
+ _request_auth=None,
144
+ ) -> RequestSerialized:
145
+ """Builds the HTTP request params needed by the request.
146
+ :param method: Method to call.
147
+ :param resource_path: Path to method endpoint.
148
+ :param path_params: Path parameters in the url.
149
+ :param query_params: Query parameters in the url.
150
+ :param header_params: Header parameters to be
151
+ placed in the request header.
152
+ :param body: Request body.
153
+ :param post_params dict: Request post form parameters,
154
+ for `application/x-www-form-urlencoded`, `multipart/form-data`.
155
+ :param auth_settings list: Auth Settings names for the request.
156
+ :param files dict: key -> filename, value -> filepath,
157
+ for `multipart/form-data`.
158
+ :param collection_formats: dict of collection formats for path, query,
159
+ header, and post parameters.
160
+ :param _request_auth: set to override the auth_settings for an a single
161
+ request; this effectively ignores the authentication
162
+ in the spec for a single request.
163
+ :return: tuple of form (path, http_method, query_params, header_params,
164
+ body, post_params, files)
165
+ """
166
+
167
+ # header parameters
168
+ header_params = header_params or {}
169
+ header_params.update(self.default_headers)
170
+ if self.cookie:
171
+ header_params["Cookie"] = self.cookie
172
+ if header_params:
173
+ header_params = self.sanitize_for_serialization(header_params)
174
+ header_params = dict(self.parameters_to_tuples(header_params, collection_formats))
175
+
176
+ # path parameters
177
+ if path_params:
178
+ path_params = self.sanitize_for_serialization(path_params)
179
+ path_params = self.parameters_to_tuples(path_params, collection_formats)
180
+ for k, v in path_params:
181
+ # specified safe chars, encode everything
182
+ resource_path = resource_path.replace("{%s}" % k, quote(str(v)))
183
+
184
+ # post parameters
185
+ if post_params or files:
186
+ post_params = post_params if post_params else []
187
+ post_params = self.sanitize_for_serialization(post_params)
188
+ post_params = self.parameters_to_tuples(post_params, collection_formats)
189
+ if files:
190
+ post_params.extend(self.files_parameters(files))
191
+
192
+ # body
193
+ if body:
194
+ body = self.sanitize_for_serialization(body)
195
+
196
+ # request url
197
+ if _host is None:
198
+ url = self.host + resource_path
199
+ else:
200
+ # use server/host defined in path or operation instead
201
+ url = _host + resource_path
202
+
203
+ # query parameters
204
+ if query_params:
205
+ query_params = self.sanitize_for_serialization(query_params)
206
+ url_query = self.parameters_to_url_query(query_params, collection_formats)
207
+ url += "?" + url_query
208
+
209
+ return method, url, header_params, body, post_params
210
+
211
+ def call_api(
212
+ self, method, url, header_params=None, body=None, post_params=None, _request_timeout=None
213
+ ) -> rest.RESTResponse:
214
+ """Makes the HTTP request (synchronous)
215
+ :param method: Method to call.
216
+ :param url: Path to method endpoint.
217
+ :param header_params: Header parameters to be
218
+ placed in the request header.
219
+ :param body: Request body.
220
+ :param post_params dict: Request post form parameters,
221
+ for `application/x-www-form-urlencoded`, `multipart/form-data`.
222
+ :param _request_timeout: timeout setting for this request.
223
+ :return: RESTResponse
224
+ """
225
+
226
+ try:
227
+ # perform request and return response
228
+ response_data = self.rest_client.request(
229
+ method,
230
+ url,
231
+ headers=header_params,
232
+ body=body,
233
+ post_params=post_params,
234
+ _request_timeout=_request_timeout,
235
+ )
236
+
237
+ except ApiException as e:
238
+ raise e
239
+
240
+ return response_data
241
+
242
+ def response_deserialize(
243
+ self, response_data: rest.RESTResponse, response_types_map: Optional[Dict[str, ApiResponseT]] = None
244
+ ) -> ApiResponse[ApiResponseT]:
245
+ """Deserializes response into an object.
246
+ :param response_data: RESTResponse object to be deserialized.
247
+ :param response_types_map: dict of response types.
248
+ :return: ApiResponse
249
+ """
250
+
251
+ msg = "RESTResponse.read() must be called before passing it to response_deserialize()"
252
+ if response_data.data is None:
253
+ raise ValueError(msg)
254
+
255
+ response_type = response_types_map.get(str(response_data.status), None)
256
+ if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599:
257
+ # if not found, look for '1XX', '2XX', etc.
258
+ response_type = response_types_map.get(str(response_data.status)[0] + "XX", None)
259
+
260
+ # deserialize response data
261
+ response_text = None
262
+ return_data = None
263
+ try:
264
+ if response_type == "bytearray":
265
+ return_data = response_data.data
266
+ elif response_type == "file":
267
+ return_data = self.__deserialize_file(response_data)
268
+ elif response_type is not None:
269
+ match = None
270
+ content_type = response_data.getheader("content-type")
271
+ if content_type is not None:
272
+ match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type)
273
+ encoding = match.group(1) if match else "utf-8"
274
+ response_text = response_data.data.decode(encoding)
275
+ return_data = self.deserialize(response_text, response_type, content_type)
276
+ finally:
277
+ if not 200 <= response_data.status <= 299:
278
+ raise ApiException.from_response(
279
+ http_resp=response_data,
280
+ body=response_text,
281
+ data=return_data,
282
+ )
283
+
284
+ return ApiResponse(
285
+ status_code=response_data.status,
286
+ data=return_data,
287
+ headers=response_data.getheaders(),
288
+ raw_data=response_data.data,
289
+ )
290
+
291
+ def sanitize_for_serialization(self, obj):
292
+ """Builds a JSON POST object.
293
+
294
+ If obj is None, return None.
295
+ If obj is SecretStr, return obj.get_secret_value()
296
+ If obj is str, int, long, float, bool, return directly.
297
+ If obj is datetime.datetime, datetime.date
298
+ convert to string in iso8601 format.
299
+ If obj is list, sanitize each element in the list.
300
+ If obj is dict, return the dict.
301
+ If obj is OpenAPI model, return the properties dict.
302
+
303
+ :param obj: The data to serialize.
304
+ :return: The serialized form of data.
305
+ """
306
+ if obj is None:
307
+ return None
308
+ elif isinstance(obj, Enum):
309
+ return obj.value
310
+ elif isinstance(obj, SecretStr):
311
+ return obj.get_secret_value()
312
+ elif isinstance(obj, self.PRIMITIVE_TYPES):
313
+ return obj
314
+ elif isinstance(obj, list):
315
+ return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj]
316
+ elif isinstance(obj, tuple):
317
+ return tuple(self.sanitize_for_serialization(sub_obj) for sub_obj in obj)
318
+ elif isinstance(obj, (datetime.datetime, datetime.date)):
319
+ return obj.isoformat()
320
+
321
+ elif isinstance(obj, dict):
322
+ obj_dict = obj
323
+ else:
324
+ # Convert model obj to dict except
325
+ # attributes `openapi_types`, `attribute_map`
326
+ # and attributes which value is not None.
327
+ # Convert attribute name to json key in
328
+ # model definition for request.
329
+ if hasattr(obj, "to_dict") and callable(obj.to_dict):
330
+ obj_dict = obj.to_dict()
331
+ else:
332
+ obj_dict = obj.__dict__
333
+
334
+ return {key: self.sanitize_for_serialization(val) for key, val in obj_dict.items()}
335
+
336
+ def deserialize(self, response_text: str, response_type: str, content_type: Optional[str]):
337
+ """Deserializes response into an object.
338
+
339
+ :param response: RESTResponse object to be deserialized.
340
+ :param response_type: class literal for
341
+ deserialized object, or string of class name.
342
+ :param content_type: content type of response.
343
+
344
+ :return: deserialized object.
345
+ """
346
+
347
+ # fetch data from response object
348
+ if content_type is None:
349
+ try:
350
+ data = json.loads(response_text)
351
+ except ValueError:
352
+ data = response_text
353
+ elif content_type.startswith("application/json"):
354
+ if response_text == "":
355
+ data = ""
356
+ else:
357
+ data = json.loads(response_text)
358
+ elif content_type.startswith("text/plain"):
359
+ data = response_text
360
+ else:
361
+ raise ApiException(status=0, reason="Unsupported content type: {0}".format(content_type))
362
+
363
+ return self.__deserialize(data, response_type)
364
+
365
+ def __deserialize(self, data, klass):
366
+ """Deserializes dict, list, str into an object.
367
+
368
+ :param data: dict, list or str.
369
+ :param klass: class literal, or string of class name.
370
+
371
+ :return: object.
372
+ """
373
+ if data is None:
374
+ return None
375
+
376
+ if isinstance(klass, str):
377
+ if klass.startswith("List["):
378
+ m = re.match(r"List\[(.*)]", klass)
379
+ if m is None:
380
+ raise ValueError("Malformed List type definition")
381
+ sub_kls = m.group(1)
382
+ return [self.__deserialize(sub_data, sub_kls) for sub_data in data]
383
+
384
+ if klass.startswith("Dict["):
385
+ m = re.match(r"Dict\[([^,]*), (.*)]", klass)
386
+ if m is None:
387
+ raise ValueError("Malformed Dict type definition")
388
+ sub_kls = m.group(2)
389
+ return {k: self.__deserialize(v, sub_kls) for k, v in data.items()}
390
+
391
+ # convert str to class
392
+ if klass in self.NATIVE_TYPES_MAPPING:
393
+ klass = self.NATIVE_TYPES_MAPPING[klass]
394
+ else:
395
+ klass = getattr(stackit.objectstorage.models, klass)
396
+
397
+ if klass in self.PRIMITIVE_TYPES:
398
+ return self.__deserialize_primitive(data, klass)
399
+ elif klass == object:
400
+ return self.__deserialize_object(data)
401
+ elif klass == datetime.date:
402
+ return self.__deserialize_date(data)
403
+ elif klass == datetime.datetime:
404
+ return self.__deserialize_datetime(data)
405
+ elif issubclass(klass, Enum):
406
+ return self.__deserialize_enum(data, klass)
407
+ else:
408
+ return self.__deserialize_model(data, klass)
409
+
410
+ def parameters_to_tuples(self, params, collection_formats):
411
+ """Get parameters as list of tuples, formatting collections.
412
+
413
+ :param params: Parameters as dict or list of two-tuples
414
+ :param dict collection_formats: Parameter collection formats
415
+ :return: Parameters as list of tuples, collections formatted
416
+ """
417
+ new_params: List[Tuple[str, str]] = []
418
+ if collection_formats is None:
419
+ collection_formats = {}
420
+ for k, v in params.items() if isinstance(params, dict) else params:
421
+ if k in collection_formats:
422
+ collection_format = collection_formats[k]
423
+ if collection_format == "multi":
424
+ new_params.extend((k, value) for value in v)
425
+ else:
426
+ if collection_format == "ssv":
427
+ delimiter = " "
428
+ elif collection_format == "tsv":
429
+ delimiter = "\t"
430
+ elif collection_format == "pipes":
431
+ delimiter = "|"
432
+ else: # csv is the default
433
+ delimiter = ","
434
+ new_params.append((k, delimiter.join(str(value) for value in v)))
435
+ else:
436
+ new_params.append((k, v))
437
+ return new_params
438
+
439
+ def parameters_to_url_query(self, params, collection_formats):
440
+ """Get parameters as list of tuples, formatting collections.
441
+
442
+ :param params: Parameters as dict or list of two-tuples
443
+ :param dict collection_formats: Parameter collection formats
444
+ :return: URL query string (e.g. a=Hello%20World&b=123)
445
+ """
446
+ new_params: List[Tuple[str, str]] = []
447
+ if collection_formats is None:
448
+ collection_formats = {}
449
+ for k, v in params.items() if isinstance(params, dict) else params:
450
+ if isinstance(v, bool):
451
+ v = str(v).lower()
452
+ if isinstance(v, (int, float)):
453
+ v = str(v)
454
+ if isinstance(v, dict):
455
+ v = json.dumps(v)
456
+
457
+ if k in collection_formats:
458
+ collection_format = collection_formats[k]
459
+ if collection_format == "multi":
460
+ new_params.extend((k, str(value)) for value in v)
461
+ else:
462
+ if collection_format == "ssv":
463
+ delimiter = " "
464
+ elif collection_format == "tsv":
465
+ delimiter = "\t"
466
+ elif collection_format == "pipes":
467
+ delimiter = "|"
468
+ else: # csv is the default
469
+ delimiter = ","
470
+ new_params.append((k, delimiter.join(quote(str(value)) for value in v)))
471
+ else:
472
+ new_params.append((k, quote(str(v))))
473
+
474
+ return "&".join(["=".join(map(str, item)) for item in new_params])
475
+
476
+ def files_parameters(self, files: Dict[str, Union[str, bytes]]):
477
+ """Builds form parameters.
478
+
479
+ :param files: File parameters.
480
+ :return: Form parameters with files.
481
+ """
482
+ params = []
483
+ for k, v in files.items():
484
+ if isinstance(v, str):
485
+ with open(v, "rb") as f:
486
+ filename = os.path.basename(f.name)
487
+ filedata = f.read()
488
+ elif isinstance(v, bytes):
489
+ filename = k
490
+ filedata = v
491
+ else:
492
+ raise ValueError("Unsupported file value")
493
+ mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream"
494
+ params.append(tuple([k, tuple([filename, filedata, mimetype])]))
495
+ return params
496
+
497
+ def select_header_accept(self, accepts: List[str]) -> Optional[str]:
498
+ """Returns `Accept` based on an array of accepts provided.
499
+
500
+ :param accepts: List of headers.
501
+ :return: Accept (e.g. application/json).
502
+ """
503
+ if not accepts:
504
+ return None
505
+
506
+ for accept in accepts:
507
+ if re.search("json", accept, re.IGNORECASE):
508
+ return accept
509
+
510
+ return accepts[0]
511
+
512
+ def select_header_content_type(self, content_types):
513
+ """Returns `Content-Type` based on an array of content_types provided.
514
+
515
+ :param content_types: List of content-types.
516
+ :return: Content-Type (e.g. application/json).
517
+ """
518
+ if not content_types:
519
+ return None
520
+
521
+ for content_type in content_types:
522
+ if re.search("json", content_type, re.IGNORECASE):
523
+ return content_type
524
+
525
+ return content_types[0]
526
+
527
+ def __deserialize_file(self, response):
528
+ """Deserializes body to file
529
+
530
+ Saves response body into a file in a temporary folder,
531
+ using the filename from the `Content-Disposition` header if provided.
532
+
533
+ handle file downloading
534
+ save response body into a tmp file and return the instance
535
+
536
+ :param response: RESTResponse.
537
+ :return: file path.
538
+ """
539
+ fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path)
540
+ os.close(fd)
541
+ os.remove(path)
542
+
543
+ content_disposition = response.getheader("Content-Disposition")
544
+ if content_disposition:
545
+ m = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition)
546
+ if m is None:
547
+ raise ValueError("Unexpected 'content-disposition' header value")
548
+ filename = m.group(1)
549
+ path = os.path.join(os.path.dirname(path), filename)
550
+
551
+ with open(path, "wb") as f:
552
+ f.write(response.data)
553
+
554
+ return path
555
+
556
+ def __deserialize_primitive(self, data, klass):
557
+ """Deserializes string to primitive type.
558
+
559
+ :param data: str.
560
+ :param klass: class literal.
561
+
562
+ :return: int, long, float, str, bool.
563
+ """
564
+ try:
565
+ return klass(data)
566
+ except UnicodeEncodeError:
567
+ return str(data)
568
+ except TypeError:
569
+ return data
570
+
571
+ def __deserialize_object(self, value):
572
+ """Return an original value.
573
+
574
+ :return: object.
575
+ """
576
+ return value
577
+
578
+ def __deserialize_date(self, string):
579
+ """Deserializes string to date.
580
+
581
+ :param string: str.
582
+ :return: date.
583
+ """
584
+ try:
585
+ return parse(string).date()
586
+ except ImportError:
587
+ return string
588
+ except ValueError:
589
+ raise rest.ApiException(status=0, reason="Failed to parse `{0}` as date object".format(string))
590
+
591
+ def __deserialize_datetime(self, string):
592
+ """Deserializes string to datetime.
593
+
594
+ The string should be in iso8601 datetime format.
595
+
596
+ :param string: str.
597
+ :return: datetime.
598
+ """
599
+ try:
600
+ return parse(string)
601
+ except ImportError:
602
+ return string
603
+ except ValueError:
604
+ raise rest.ApiException(status=0, reason=("Failed to parse `{0}` as datetime object".format(string)))
605
+
606
+ def __deserialize_enum(self, data, klass):
607
+ """Deserializes primitive type to enum.
608
+
609
+ :param data: primitive type.
610
+ :param klass: class literal.
611
+ :return: enum value.
612
+ """
613
+ try:
614
+ return klass(data)
615
+ except ValueError:
616
+ raise rest.ApiException(status=0, reason=("Failed to parse `{0}` as `{1}`".format(data, klass)))
617
+
618
+ def __deserialize_model(self, data, klass):
619
+ """Deserializes list or dict to model.
620
+
621
+ :param data: dict, list.
622
+ :param klass: class literal.
623
+ :return: model object.
624
+ """
625
+
626
+ return klass.from_dict(data)
@@ -0,0 +1,23 @@
1
+ """API response object."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Generic, Mapping, Optional, TypeVar
6
+
7
+ from pydantic import BaseModel, Field, StrictBytes, StrictInt
8
+
9
+
10
+ T = TypeVar("T")
11
+
12
+
13
+ class ApiResponse(BaseModel, Generic[T]):
14
+ """
15
+ API response object
16
+ """
17
+
18
+ status_code: StrictInt = Field(description="HTTP status code")
19
+ headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers")
20
+ data: T = Field(description="Deserialized data given the data type")
21
+ raw_data: StrictBytes = Field(description="Raw data (HTTP response body)")
22
+
23
+ model_config = {"arbitrary_types_allowed": True}