whistic 0.0.1__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.
@@ -0,0 +1,248 @@
1
+ Metadata-Version: 2.4
2
+ Name: whistic
3
+ Version: 0.0.1
4
+ Summary: Python SDK to interface with the Whistic API
5
+ Home-page: https://github.com/massyn/whistic
6
+ Author: Phil Massyn
7
+ Author-email: Phil Massyn <phil.massyn@icloud.com>
8
+ Maintainer-email: Phil Massyn <phil.massyn@icloud.com>
9
+ License: MIT License
10
+
11
+ Copyright (c) 2025 Phil Massyn
12
+
13
+ Permission is hereby granted, free of charge, to any person obtaining a copy
14
+ of this software and associated documentation files (the "Software"), to deal
15
+ in the Software without restriction, including without limitation the rights
16
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
+ copies of the Software, and to permit persons to whom the Software is
18
+ furnished to do so, subject to the following conditions:
19
+
20
+ The above copyright notice and this permission notice shall be included in all
21
+ copies or substantial portions of the Software.
22
+
23
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
+ SOFTWARE.
30
+
31
+ Project-URL: Homepage, https://github.com/massyn/whistic
32
+ Project-URL: Bug Tracker, https://github.com/massyn/whistic/issues
33
+ Project-URL: Documentation, https://github.com/massyn/whistic#readme
34
+ Project-URL: Source Code, https://github.com/massyn/whistic
35
+ Keywords: whistic,api,sdk,vendor,management,third-party,risk
36
+ Classifier: Development Status :: 4 - Beta
37
+ Classifier: Intended Audience :: Developers
38
+ Classifier: License :: OSI Approved :: MIT License
39
+ Classifier: Operating System :: OS Independent
40
+ Classifier: Programming Language :: Python :: 3
41
+ Classifier: Programming Language :: Python :: 3.7
42
+ Classifier: Programming Language :: Python :: 3.8
43
+ Classifier: Programming Language :: Python :: 3.9
44
+ Classifier: Programming Language :: Python :: 3.10
45
+ Classifier: Programming Language :: Python :: 3.11
46
+ Classifier: Programming Language :: Python :: 3.12
47
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
48
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
49
+ Classifier: Topic :: Security
50
+ Requires-Python: >=3.7
51
+ Description-Content-Type: text/markdown
52
+ License-File: LICENSE
53
+ Requires-Dist: requests>=2.25.0
54
+ Requires-Dist: python-dotenv>=0.19.0
55
+ Requires-Dist: colorama>=0.4.4
56
+ Dynamic: author
57
+ Dynamic: home-page
58
+ Dynamic: license-file
59
+ Dynamic: requires-python
60
+
61
+ # Whistic SDK
62
+
63
+ A Python SDK to interface with the Whistic API for vendor management and third-party risk management operations.
64
+
65
+ ## Installation
66
+
67
+ ### From PyPI (Recommended)
68
+
69
+ ```bash
70
+ pip install whistic
71
+ ```
72
+
73
+ ### From Source
74
+
75
+ ```bash
76
+ git clone https://github.com/massyn/whistic.git
77
+ cd whistic
78
+ pip install -e .
79
+ ```
80
+
81
+ ## Requirements
82
+
83
+ * Python 3.7 or higher
84
+ * Create an [API Key](https://whistichelp.zendesk.com/hc/en-us/articles/14823790530071-API-Key-Creation) on the Whistic platform
85
+
86
+ ## Quick Start
87
+
88
+ ### Environment Setup
89
+
90
+ Create a `.env` file in your project root or set the environment variable:
91
+
92
+ ```bash
93
+ export WHISTIC_TOKEN=your_api_token_here
94
+ ```
95
+
96
+ Or create a `.env` file:
97
+ ```
98
+ WHISTIC_TOKEN=your_api_token_here
99
+ ```
100
+
101
+ ### Basic Usage
102
+
103
+ ```python
104
+ from whistic_sdk import Whistic
105
+ from dotenv import load_dotenv
106
+
107
+ # Load environment variables
108
+ load_dotenv()
109
+
110
+ # Initialize the client
111
+ client = Whistic()
112
+
113
+ # List all vendors
114
+ vendors = client.vendors.list()
115
+ print(f"Found {len(vendors)} vendors")
116
+
117
+ # Get detailed information for all vendors (parallel processing)
118
+ detailed_vendors = client.vendors.describe()
119
+
120
+ # Get a specific vendor
121
+ vendor_id = vendors[0]['identifier']
122
+ vendor_details = client.vendors.get(vendor_id)
123
+
124
+ # Update a vendor
125
+ client.vendors.update(vendor_id, {
126
+ "name": "Updated Vendor Name",
127
+ "description": "Updated description"
128
+ })
129
+
130
+ # Create a new vendor
131
+ new_vendor_data = {
132
+ "name": "New Vendor",
133
+ "description": "A new vendor",
134
+ # ... other vendor fields
135
+ }
136
+ client.vendors.new(new_vendor_data)
137
+ ```
138
+
139
+ ## Advanced Usage
140
+
141
+ ### Custom Configuration
142
+
143
+ ```python
144
+ from whistic_sdk import Whistic
145
+
146
+ # Configure with custom settings
147
+ client = Whistic(max_workers=10) # Increase parallel processing workers
148
+ ```
149
+
150
+ ### Batch Operations
151
+
152
+ ```python
153
+ # Process all vendors in parallel
154
+ all_vendors = client.vendors.describe()
155
+
156
+ # Filter and update multiple vendors
157
+ for vendor in all_vendors:
158
+ if vendor.get('status') == 'pending':
159
+ client.vendors.update(vendor['identifier'], {
160
+ 'status': 'active'
161
+ })
162
+ ```
163
+
164
+ ### Error Handling
165
+
166
+ ```python
167
+ import logging
168
+
169
+ # Enable debug logging to see API calls
170
+ logging.basicConfig(level=logging.DEBUG)
171
+
172
+ try:
173
+ vendor = client.vendors.get('non-existent-id')
174
+ except Exception as e:
175
+ print(f"Error fetching vendor: {e}")
176
+ ```
177
+
178
+ ## API Reference
179
+
180
+ ### Whistic Class
181
+
182
+ The main client class for interacting with the Whistic API.
183
+
184
+ #### Constructor
185
+ - `Whistic(max_workers=5)`: Initialize client with optional max workers for parallel processing
186
+
187
+ #### Properties
188
+ - `vendors`: Access to vendor management operations
189
+
190
+ ### Vendors Class
191
+
192
+ Handles all vendor-related operations.
193
+
194
+ #### Methods
195
+
196
+ - **`list()`**: Get paginated list of all vendor identifiers
197
+ - Returns: List of vendor objects with basic information
198
+
199
+ - **`describe()`**: Get detailed information for all vendors using parallel processing
200
+ - Returns: List of complete vendor objects with all details
201
+
202
+ - **`get(vendor_id)`**: Fetch detailed information for a specific vendor
203
+ - Parameters: `vendor_id` (str) - The vendor identifier
204
+ - Returns: Complete vendor object or None if not found
205
+
206
+ - **`update(vendor_id, data)`**: Update vendor information
207
+ - Parameters:
208
+ - `vendor_id` (str) - The vendor identifier
209
+ - `data` (dict) - Dictionary with fields to update
210
+ - Note: Uses deep merge to preserve existing data
211
+
212
+ - **`new(data)`**: Create a new vendor
213
+ - Parameters: `data` (dict) - Complete vendor data structure
214
+
215
+ ## Features
216
+
217
+ - **Automatic Pagination**: Handles API pagination automatically
218
+ - **Parallel Processing**: Concurrent API calls for better performance
219
+ - **Rate Limiting**: Built-in retry logic with exponential backoff
220
+ - **Deep Merge Updates**: Safely update vendor data without losing existing fields
221
+ - **Colored Logging**: Enhanced console output for debugging
222
+ - **Environment Variable Support**: Secure token management
223
+
224
+ ## Error Handling
225
+
226
+ The SDK includes comprehensive error handling:
227
+
228
+ - **Rate Limiting**: Automatic retry with exponential backoff for 429 responses
229
+ - **Request Timeouts**: 30-second timeout on all API calls
230
+ - **Connection Errors**: Graceful handling of network issues
231
+ - **API Errors**: Detailed error logging with response codes and messages
232
+
233
+ ## Contributing
234
+
235
+ 1. Fork the repository
236
+ 2. Create a feature branch
237
+ 3. Make your changes
238
+ 4. Add tests if applicable
239
+ 5. Submit a pull request
240
+
241
+ ## License
242
+
243
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
244
+
245
+ ## Reference
246
+
247
+ * [Whistic API Documentation](https://public.whistic.com/swagger-ui/index.html)
248
+ * [API Key Creation Guide](https://whistichelp.zendesk.com/hc/en-us/articles/14823790530071-API-Key-Creation)
@@ -0,0 +1,8 @@
1
+ whistic-0.0.1.dist-info/licenses/LICENSE,sha256=TDoSAO4q0OHg65s4Pvg0eBMSyVn-LMQeUUyU1-_9CPc,1068
2
+ whistic_sdk/__init__.py,sha256=7tMzUZhECPGfPF3KRBWQ_sSbzmccHNSRLhfNYHfSUbA,460
3
+ whistic_sdk/vendors.py,sha256=wWAfn1qEivpNKPmz1HrTnBW-R_TYqt6l5eFiM9cJIlk,4248
4
+ whistic_sdk/whistic.py,sha256=CQDnL8Oo8YDQ7qr5HzZbBZhQIkXVjXj4pN_6fkLrPaQ,3735
5
+ whistic-0.0.1.dist-info/METADATA,sha256=Pn2yh3EIGc66FoAMffH4RpYRt8QnMOo717pezQCYXQU,7451
6
+ whistic-0.0.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
7
+ whistic-0.0.1.dist-info/top_level.txt,sha256=xS3bIer_adpKGWYAysft7zmVNs4qdQ9ADyz4w48oWC0,12
8
+ whistic-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Phil Massyn
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ whistic_sdk
@@ -0,0 +1,16 @@
1
+ """
2
+ Whistic SDK - Python SDK to interface with the Whistic API
3
+
4
+ This package provides a simple and intuitive way to interact with the Whistic API
5
+ for vendor management and third-party risk management operations.
6
+ """
7
+
8
+ from .whistic import Whistic
9
+ from .vendors import Vendors
10
+
11
+ __version__ = "0.0.1"
12
+ __author__ = "Phil Massyn"
13
+ __email__ = "phil.massyn@icloud.com"
14
+ __description__ = "Python SDK to interface with the Whistic API"
15
+
16
+ __all__ = ["Whistic", "Vendors"]
whistic_sdk/vendors.py ADDED
@@ -0,0 +1,107 @@
1
+ import requests
2
+ import logging
3
+ from concurrent.futures import ThreadPoolExecutor, as_completed
4
+
5
+
6
+ class Vendors:
7
+ def __init__(self, whistic_instance):
8
+ self.whistic = whistic_instance
9
+
10
+ def list(self):
11
+ logging.debug("Querying vendors")
12
+ url = f"{self.whistic.endpoint}/vendors?page_size={self.whistic.page_size}"
13
+
14
+ all_vendor_identifiers = []
15
+
16
+ while True:
17
+ response = self.whistic._make_request_with_retry(url)
18
+
19
+ if response and response.status_code == 200:
20
+ logging.info(f"{response.status_code} - {url}")
21
+ response_data = response.json()
22
+
23
+ for v in response_data['_embedded']['vendors']:
24
+ all_vendor_identifiers.append(v)
25
+
26
+ if 'next' in response_data['_links']:
27
+ next_url = response_data['_links']['next']['href']
28
+ if next_url == url:
29
+ break
30
+ else:
31
+ url = next_url
32
+ else:
33
+ break
34
+ else:
35
+ break
36
+
37
+ logging.info(f"Found {len(all_vendor_identifiers)} vendors. Fetching details in parallel...")
38
+ return all_vendor_identifiers
39
+
40
+ def describe(self):
41
+ all_vendor_identifiers = []
42
+ for v in self.list():
43
+ all_vendor_identifiers.append(v['identifier'])
44
+ data = []
45
+ with ThreadPoolExecutor(max_workers=self.whistic.max_workers) as executor:
46
+ future_to_identifier = {executor.submit(self.get, identifier): identifier
47
+ for identifier in all_vendor_identifiers}
48
+
49
+ for future in as_completed(future_to_identifier):
50
+ identifier = future_to_identifier[future]
51
+ try:
52
+ vendor_data = future.result()
53
+ if vendor_data:
54
+ data.append(vendor_data)
55
+ except Exception as e:
56
+ logging.error(f"Failed to fetch vendor {identifier}: {e}")
57
+
58
+ logging.info(f"Successfully retrieved {len(data)} vendors")
59
+ return data
60
+
61
+ def get(self, vendor_id):
62
+ """Fetch individual vendor details"""
63
+ url = f"{self.whistic.endpoint}/vendors/{vendor_id}"
64
+ response = self.whistic._make_request_with_retry(url)
65
+
66
+ if response and response.status_code == 200:
67
+ logging.info(f"{response.status_code} - {url}")
68
+ return response.json()
69
+ else:
70
+ if response:
71
+ logging.error(f"{response.status_code} - {url} - {response.content}")
72
+ return None
73
+
74
+ def _deep_merge(self, orig, update_data):
75
+ """Recursively merge update_data into orig, only updating existing keys"""
76
+ for key, value in update_data.items():
77
+ if key not in orig:
78
+ logging.warning(f"Key '{key}' not found in original data, skipping")
79
+ continue
80
+
81
+ if isinstance(value, dict) and isinstance(orig[key], dict):
82
+ # Recursively merge nested dictionaries
83
+ self._deep_merge(orig[key], value)
84
+ else:
85
+ # Update the value directly
86
+ orig[key] = value
87
+
88
+ def update(self, vendor_id, data):
89
+ url = f"{self.whistic.endpoint}/vendors/{vendor_id}?ignore_missing_custom_fields=true"
90
+ orig = self.get(vendor_id)
91
+
92
+ # Deep merge the data into orig
93
+ self._deep_merge(orig, data)
94
+
95
+ response = requests.put(url, json=orig, headers=self.whistic.headers, timeout=30)
96
+ if response.status_code == 200:
97
+ logging.info(f"{response.status_code} - {url}")
98
+ else:
99
+ logging.error(f"{response.status_code} - {url} - {response.content}")
100
+
101
+ def new(self, data):
102
+ url = f"{self.whistic.endpoint}/vendors?ignore_missing_custom_fields=true"
103
+ response = requests.post(url, json=data, headers=self.whistic.headers, timeout=30)
104
+ if response.status_code == 200:
105
+ logging.info(f"{response.status_code} - {url}")
106
+ else:
107
+ logging.error(f"{response.status_code} - {url} - {response.content}")
whistic_sdk/whistic.py ADDED
@@ -0,0 +1,109 @@
1
+ import requests
2
+ import os
3
+ import logging
4
+ from dotenv import load_dotenv
5
+ import json
6
+ import time
7
+ import random
8
+ from .vendors import Vendors
9
+
10
+ try:
11
+ import colorama
12
+ colorama.init()
13
+ except ImportError:
14
+ os.system('') # Enables ANSI escape characters in terminal on Windows
15
+
16
+ class ColorFormatter(logging.Formatter):
17
+ COLORS = {
18
+ 'DEBUG': '\033[36m', # Cyan
19
+ 'INFO': '\033[32m', # Green
20
+ 'WARNING': '\033[33m', # Yellow
21
+ 'ERROR': '\033[31m', # Red
22
+ 'CRITICAL': '\033[41m', # Red background
23
+ }
24
+ RESET = '\033[0m'
25
+
26
+ def format(self, record):
27
+ # Center the levelname in a field of width 8
28
+ levelname = record.levelname.center(8)
29
+ color = self.COLORS.get(record.levelname.strip(), '')
30
+ record.levelname = f"{color}{levelname}{self.RESET}"
31
+ return super().format(record)
32
+
33
+ handler = logging.StreamHandler()
34
+ handler.setFormatter(ColorFormatter('%(asctime)s - %(levelname)s %(message)s'))
35
+ logging.basicConfig(level=logging.INFO, handlers=[handler])
36
+
37
+
38
+ class Whistic:
39
+ def __init__(self, max_workers=5):
40
+ self.endpoint = "https://public.whistic.com/api"
41
+ self.page_size = 25
42
+ self.max_workers = max_workers
43
+
44
+ if not 'WHISTIC_TOKEN' in os.environ:
45
+ logging.critical("The Whistic module cannot initiate without the WHISTIC_TOKEN being defined")
46
+ exit(1)
47
+ else:
48
+ logging.info("Whistic token found")
49
+
50
+ self.headers = {
51
+ 'accept' : 'application/json',
52
+ 'api-key' : os.environ['WHISTIC_TOKEN']
53
+ }
54
+
55
+ self.vendors = Vendors(self)
56
+
57
+ def _make_request_with_retry(self, url, max_retries=3):
58
+ """Make a request with exponential backoff for rate limiting"""
59
+ for attempt in range(max_retries + 1):
60
+ try:
61
+ response = requests.get(url, headers=self.headers, timeout=30)
62
+
63
+ if response.status_code == 200:
64
+ return response
65
+ elif response.status_code == 429:
66
+ if attempt < max_retries:
67
+ wait_time = (2 ** attempt) + random.uniform(0, 1)
68
+ logging.warning(f"Rate limit hit (429). Retrying in {wait_time:.2f} seconds...")
69
+ time.sleep(wait_time)
70
+ continue
71
+ else:
72
+ logging.error(f"Rate limit exceeded after {max_retries} retries: {url}")
73
+ return response
74
+ else:
75
+ logging.error(f"{response.status_code} - {url} - {response.content}")
76
+ return response
77
+
78
+ except requests.exceptions.RequestException as e:
79
+ if attempt < max_retries:
80
+ wait_time = (2 ** attempt) + random.uniform(0, 1)
81
+ logging.warning(f"Request failed: {e}. Retrying in {wait_time:.2f} seconds...")
82
+ time.sleep(wait_time)
83
+ else:
84
+ logging.error(f"Request failed after {max_retries} retries: {e}")
85
+ raise
86
+
87
+ return None
88
+
89
+ if __name__ == '__main__':
90
+ load_dotenv()
91
+
92
+ W = Whistic()
93
+
94
+ # Reading all vendors
95
+ my_vendors = W.vendors.list()
96
+
97
+ with open('_vendors.json','wt') as q:
98
+ q.write(json.dumps(my_vendors,indent=2))
99
+
100
+ # == read just one vendor
101
+ id = my_vendors[10]['identifier']
102
+ my_vendor = W.vendors.get(id)
103
+
104
+ # == Update a vendor
105
+ W.vendors.update(id,{ "name" : "HOWDY"} )
106
+
107
+ # == add a new vendor
108
+ #W.vendors.new(data)
109
+