laceworksdk.api.base_endpoint

  1# -*- coding: utf-8 -*-
  2
  3class BaseEndpoint:
  4    """
  5    A class used to implement base functionality for Lacework API Endpoints
  6    """
  7
  8    def __init__(self,
  9                 session,
 10                 object_type,
 11                 endpoint_root="/api/v2"):
 12        """
 13        :param session: An instance of the HttpSession class.
 14        :param object_type: The Lacework object type to use.
 15        :param endpoint_root: The URL endpoint root to use.
 16        """
 17
 18        super().__init__()
 19        self._session = session
 20        self._object_type = object_type
 21        self._endpoint_root = endpoint_root
 22
 23    def build_dict_from_items(self, *dicts, **items):
 24        """
 25        A method to build a dictionary based on inputs, pruning items that are None.
 26
 27        :returns: A single dict built from the input.
 28        """
 29
 30        dict_list = list(dicts)
 31        dict_list.append(items)
 32        result = {}
 33
 34        for dictionary in dict_list:
 35            result = {**result, **self._convert_dictionary(dictionary, list(result.keys()))}
 36
 37        return result
 38
 39    def build_url(self, id=None, resource=None, action=None):
 40        """
 41        Builds the URL to use based on the endpoint path, resource, type, and ID.
 42
 43        :param id: A string representing the ID of an object to use in the URL
 44        :param resource: A string representing the type of resource to append to the URL
 45        :param action: A string representing the type of action to append to the URL
 46        """
 47
 48        result = f"{self._endpoint_root}/{self._object_type}"
 49
 50        if resource:
 51            result += f"/{resource}"
 52        if action:
 53            result += f"/{action}"
 54        if id:
 55            result += f"/{id}"
 56
 57        return result
 58
 59    @staticmethod
 60    def _convert_lower_camel_case(param_name):
 61        """
 62        Convert a Pythonic variable name to lowerCamelCase.
 63
 64        This function will take an underscored parameter name like 'query_text' and convert it
 65        to lowerCamelCase of 'queryText'.  If a parameter with no underscores is provided, it will
 66        assume that the value is already in lowerCamelCase format.
 67        """
 68
 69        words = param_name.split("_")
 70        first_word = words[0]
 71
 72        if len(words) == 1:
 73            return first_word
 74
 75        word_string = "".join([x.capitalize() or "_" for x in words[1:]])
 76
 77        return f"{first_word}{word_string}"
 78
 79    def _convert_dictionary(self, dictionary, existing_keys):
 80        """
 81        Iteratively process a dictionary to convert it to expected JSON
 82
 83        :raises KeyError: In case there is a duplicate key name in the dictionary.
 84        :returns: A single dictionary of lowerCamelCase key/value pairs.
 85        """
 86
 87        result = {}
 88
 89        for key, value in dictionary.items():
 90            camel_key = self._convert_lower_camel_case(key)
 91
 92            if value is None:
 93                continue
 94            if camel_key in existing_keys:
 95                raise KeyError(f"Attempted to insert duplicate key '{camel_key}'")
 96            if isinstance(value, dict):
 97                value = self._convert_dictionary(value, [])
 98
 99            existing_keys.append(camel_key)
100            result[camel_key] = value
101
102        return result
103
104    def _get_schema(self, subtype=None):
105        """
106        Get the schema for the current object type.
107        """
108        if subtype:
109            url = f"/api/v2/schemas/{self._object_type}/{subtype}"
110        else:
111            url = f"/api/v2/schemas/{self._object_type}"
112
113        response = self._session.get(url)
114
115        return response.json()
116
117    @property
118    def session(self):
119        """
120        Get the :class:`HttpSession` instance the object is using.
121        """
122
123        return self._session
124
125    def validate_json(self, json, subtype=None):
126        """
127        TODO: A method to validate the provided JSON based on the schema of the current object.
128        """
129
130        schema = self._get_schema(subtype)
131
132        # TODO: perform validation here
133
134        return schema
135
136    def __repr__(self):
137        if hasattr(self, "id"):
138            return "<%s %s>" % (self.__class__.__name__, self.id)
class BaseEndpoint:
  4class BaseEndpoint:
  5    """
  6    A class used to implement base functionality for Lacework API Endpoints
  7    """
  8
  9    def __init__(self,
 10                 session,
 11                 object_type,
 12                 endpoint_root="/api/v2"):
 13        """
 14        :param session: An instance of the HttpSession class.
 15        :param object_type: The Lacework object type to use.
 16        :param endpoint_root: The URL endpoint root to use.
 17        """
 18
 19        super().__init__()
 20        self._session = session
 21        self._object_type = object_type
 22        self._endpoint_root = endpoint_root
 23
 24    def build_dict_from_items(self, *dicts, **items):
 25        """
 26        A method to build a dictionary based on inputs, pruning items that are None.
 27
 28        :returns: A single dict built from the input.
 29        """
 30
 31        dict_list = list(dicts)
 32        dict_list.append(items)
 33        result = {}
 34
 35        for dictionary in dict_list:
 36            result = {**result, **self._convert_dictionary(dictionary, list(result.keys()))}
 37
 38        return result
 39
 40    def build_url(self, id=None, resource=None, action=None):
 41        """
 42        Builds the URL to use based on the endpoint path, resource, type, and ID.
 43
 44        :param id: A string representing the ID of an object to use in the URL
 45        :param resource: A string representing the type of resource to append to the URL
 46        :param action: A string representing the type of action to append to the URL
 47        """
 48
 49        result = f"{self._endpoint_root}/{self._object_type}"
 50
 51        if resource:
 52            result += f"/{resource}"
 53        if action:
 54            result += f"/{action}"
 55        if id:
 56            result += f"/{id}"
 57
 58        return result
 59
 60    @staticmethod
 61    def _convert_lower_camel_case(param_name):
 62        """
 63        Convert a Pythonic variable name to lowerCamelCase.
 64
 65        This function will take an underscored parameter name like 'query_text' and convert it
 66        to lowerCamelCase of 'queryText'.  If a parameter with no underscores is provided, it will
 67        assume that the value is already in lowerCamelCase format.
 68        """
 69
 70        words = param_name.split("_")
 71        first_word = words[0]
 72
 73        if len(words) == 1:
 74            return first_word
 75
 76        word_string = "".join([x.capitalize() or "_" for x in words[1:]])
 77
 78        return f"{first_word}{word_string}"
 79
 80    def _convert_dictionary(self, dictionary, existing_keys):
 81        """
 82        Iteratively process a dictionary to convert it to expected JSON
 83
 84        :raises KeyError: In case there is a duplicate key name in the dictionary.
 85        :returns: A single dictionary of lowerCamelCase key/value pairs.
 86        """
 87
 88        result = {}
 89
 90        for key, value in dictionary.items():
 91            camel_key = self._convert_lower_camel_case(key)
 92
 93            if value is None:
 94                continue
 95            if camel_key in existing_keys:
 96                raise KeyError(f"Attempted to insert duplicate key '{camel_key}'")
 97            if isinstance(value, dict):
 98                value = self._convert_dictionary(value, [])
 99
100            existing_keys.append(camel_key)
101            result[camel_key] = value
102
103        return result
104
105    def _get_schema(self, subtype=None):
106        """
107        Get the schema for the current object type.
108        """
109        if subtype:
110            url = f"/api/v2/schemas/{self._object_type}/{subtype}"
111        else:
112            url = f"/api/v2/schemas/{self._object_type}"
113
114        response = self._session.get(url)
115
116        return response.json()
117
118    @property
119    def session(self):
120        """
121        Get the :class:`HttpSession` instance the object is using.
122        """
123
124        return self._session
125
126    def validate_json(self, json, subtype=None):
127        """
128        TODO: A method to validate the provided JSON based on the schema of the current object.
129        """
130
131        schema = self._get_schema(subtype)
132
133        # TODO: perform validation here
134
135        return schema
136
137    def __repr__(self):
138        if hasattr(self, "id"):
139            return "<%s %s>" % (self.__class__.__name__, self.id)

A class used to implement base functionality for Lacework API Endpoints

BaseEndpoint(session, object_type, endpoint_root='/api/v2')
 9    def __init__(self,
10                 session,
11                 object_type,
12                 endpoint_root="/api/v2"):
13        """
14        :param session: An instance of the HttpSession class.
15        :param object_type: The Lacework object type to use.
16        :param endpoint_root: The URL endpoint root to use.
17        """
18
19        super().__init__()
20        self._session = session
21        self._object_type = object_type
22        self._endpoint_root = endpoint_root
Parameters
  • session: An instance of the HttpSession class.
  • object_type: The Lacework object type to use.
  • endpoint_root: The URL endpoint root to use.
def build_dict_from_items(self, *dicts, **items):
24    def build_dict_from_items(self, *dicts, **items):
25        """
26        A method to build a dictionary based on inputs, pruning items that are None.
27
28        :returns: A single dict built from the input.
29        """
30
31        dict_list = list(dicts)
32        dict_list.append(items)
33        result = {}
34
35        for dictionary in dict_list:
36            result = {**result, **self._convert_dictionary(dictionary, list(result.keys()))}
37
38        return result

A method to build a dictionary based on inputs, pruning items that are None.

:returns: A single dict built from the input.

def build_url(self, id=None, resource=None, action=None):
40    def build_url(self, id=None, resource=None, action=None):
41        """
42        Builds the URL to use based on the endpoint path, resource, type, and ID.
43
44        :param id: A string representing the ID of an object to use in the URL
45        :param resource: A string representing the type of resource to append to the URL
46        :param action: A string representing the type of action to append to the URL
47        """
48
49        result = f"{self._endpoint_root}/{self._object_type}"
50
51        if resource:
52            result += f"/{resource}"
53        if action:
54            result += f"/{action}"
55        if id:
56            result += f"/{id}"
57
58        return result

Builds the URL to use based on the endpoint path, resource, type, and ID.

Parameters
  • id: A string representing the ID of an object to use in the URL
  • resource: A string representing the type of resource to append to the URL
  • action: A string representing the type of action to append to the URL
session

Get the HttpSession instance the object is using.

def validate_json(self, json, subtype=None):
126    def validate_json(self, json, subtype=None):
127        """
128        TODO: A method to validate the provided JSON based on the schema of the current object.
129        """
130
131        schema = self._get_schema(subtype)
132
133        # TODO: perform validation here
134
135        return schema

TODO: A method to validate the provided JSON based on the schema of the current object.