das-cli 1.5.272__tar.gz → 1.6.0__tar.gz

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 (43) hide show
  1. {das_cli-1.5.272/das_cli.egg-info → das_cli-1.6.0}/PKG-INFO +41 -1
  2. {das_cli-1.5.272 → das_cli-1.6.0}/README.md +41 -1
  3. {das_cli-1.5.272 → das_cli-1.6.0}/das/authentication/auth.py +23 -5
  4. {das_cli-1.5.272 → das_cli-1.6.0}/das/cli.py +64 -5
  5. das_cli-1.6.0/das/common/api.py +177 -0
  6. {das_cli-1.5.272 → das_cli-1.6.0}/das/common/config.py +188 -2
  7. {das_cli-1.5.272 → das_cli-1.6.0}/das/common/enums.py +14 -0
  8. das_cli-1.6.0/das/common/errors.py +93 -0
  9. {das_cli-1.5.272 → das_cli-1.6.0}/das/managers/digital_objects_manager.py +81 -15
  10. {das_cli-1.5.272 → das_cli-1.6.0}/das/managers/entries_manager.py +78 -21
  11. {das_cli-1.5.272 → das_cli-1.6.0}/das/managers/search_manager.py +30 -6
  12. {das_cli-1.5.272 → das_cli-1.6.0}/das/services/attributes.py +4 -3
  13. {das_cli-1.5.272 → das_cli-1.6.0}/das/services/cache.py +4 -3
  14. {das_cli-1.5.272 → das_cli-1.6.0}/das/services/das_elastic_search.py +2 -5
  15. {das_cli-1.5.272 → das_cli-1.6.0}/das/services/digital_objects.py +59 -30
  16. {das_cli-1.5.272 → das_cli-1.6.0}/das/services/downloads.py +4 -6
  17. {das_cli-1.5.272 → das_cli-1.6.0}/das/services/entries.py +2 -9
  18. {das_cli-1.5.272 → das_cli-1.6.0}/das/services/entry_fields.py +2 -5
  19. {das_cli-1.5.272 → das_cli-1.6.0}/das/services/hangfire.py +2 -1
  20. {das_cli-1.5.272 → das_cli-1.6.0}/das/services/search.py +2 -4
  21. {das_cli-1.5.272 → das_cli-1.6.0}/das/services/users.py +2 -1
  22. {das_cli-1.5.272 → das_cli-1.6.0/das_cli.egg-info}/PKG-INFO +41 -1
  23. {das_cli-1.5.272 → das_cli-1.6.0}/das_cli.egg-info/SOURCES.txt +1 -0
  24. {das_cli-1.5.272 → das_cli-1.6.0}/pyproject.toml +1 -1
  25. das_cli-1.5.272/das/common/api.py +0 -120
  26. {das_cli-1.5.272 → das_cli-1.6.0}/LICENSE +0 -0
  27. {das_cli-1.5.272 → das_cli-1.6.0}/MANIFEST.in +0 -0
  28. {das_cli-1.5.272 → das_cli-1.6.0}/das/__init__.py +0 -0
  29. {das_cli-1.5.272 → das_cli-1.6.0}/das/ai/plugins/dasai.py +0 -0
  30. {das_cli-1.5.272 → das_cli-1.6.0}/das/ai/plugins/entries/entries_plugin.py +0 -0
  31. {das_cli-1.5.272 → das_cli-1.6.0}/das/app.py +0 -0
  32. {das_cli-1.5.272 → das_cli-1.6.0}/das/authentication/oauth.py +0 -0
  33. {das_cli-1.5.272 → das_cli-1.6.0}/das/authentication/secure_input.py +0 -0
  34. {das_cli-1.5.272 → das_cli-1.6.0}/das/common/entry_fields_constants.py +0 -0
  35. {das_cli-1.5.272 → das_cli-1.6.0}/das/common/file_utils.py +0 -0
  36. {das_cli-1.5.272 → das_cli-1.6.0}/das/managers/__init__.py +0 -0
  37. {das_cli-1.5.272 → das_cli-1.6.0}/das/managers/download_manager.py +0 -0
  38. {das_cli-1.5.272 → das_cli-1.6.0}/das/services/service_base.py +0 -0
  39. {das_cli-1.5.272 → das_cli-1.6.0}/das_cli.egg-info/dependency_links.txt +0 -0
  40. {das_cli-1.5.272 → das_cli-1.6.0}/das_cli.egg-info/entry_points.txt +0 -0
  41. {das_cli-1.5.272 → das_cli-1.6.0}/das_cli.egg-info/requires.txt +0 -0
  42. {das_cli-1.5.272 → das_cli-1.6.0}/das_cli.egg-info/top_level.txt +0 -0
  43. {das_cli-1.5.272 → das_cli-1.6.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: das-cli
3
- Version: 1.5.272
3
+ Version: 1.6.0
4
4
  Summary: DAS api client.
5
5
  Author: Royal Netherlands Institute for Sea Research
6
6
  License-Expression: MIT
@@ -79,6 +79,7 @@ das entry get --code zb.b.1ub
79
79
  - [Digital Objects](#digital-objects)
80
80
  - [Downloads](#downloads)
81
81
  - [Other CLI groups](#other-cli-groups)
82
+ - [Logging](#logging)
82
83
 
83
84
  ### Authentication
84
85
 
@@ -214,8 +215,37 @@ das config ssl-verify true
214
215
  das config ssl-status
215
216
  das config show
216
217
  das config reset --force
218
+
219
+ # Logging
220
+ das config log-level DEBUG # TRACE, DEBUG, INFO, WARN (default), ERROR, FATAL
221
+ das config log-file C:\logs\das.log # also write logs to a file
222
+ das config log-file --clear # back to console only
217
223
  ```
218
224
 
225
+ #### Logging
226
+
227
+ The CLI logs diagnostics (HTTP requests and error details) through the `das`
228
+ logger. Control how much is shown and where it goes:
229
+
230
+ - **Level** — from most to least verbose: `TRACE`, `DEBUG`, `INFO`, `WARN`
231
+ (default), `ERROR`, `FATAL`. Set with `das config log-level <LEVEL>` or the
232
+ `DAS_LOG_LEVEL` environment variable.
233
+ - **Destination** — logs go to the console by default. Also write them to a file
234
+ with `das config log-file <path>` (parent folders are created automatically)
235
+ or the `DAS_LOG_FILE` environment variable; use `das config log-file --clear`
236
+ to go back to console-only. The file log includes timestamps and logger names
237
+ while the console stays terse.
238
+
239
+ ```bash
240
+ # Verbose troubleshooting session written to a file
241
+ das config log-level DEBUG
242
+ das config log-file C:\logs\das.log
243
+ das search entries --attribute Cruise --query "cruisecode(*64PE*)"
244
+ ```
245
+
246
+ > Tip: this is the diagnostic log for the CLI itself. For an entry's
247
+ > change/audit history, use [`das entry logs`](#logs-and-ownership) instead.
248
+
219
249
  ## Programmatic Usage (Python)
220
250
 
221
251
  Two common patterns are supported.
@@ -774,6 +804,10 @@ DAS_API_URL=https://api.das-dev.nioz.nl
774
804
  DAS_API_KEY=
775
805
  VERIFY_SSL=True
776
806
 
807
+ # Logging
808
+ DAS_LOG_LEVEL=WARN
809
+ DAS_LOG_FILE=
810
+
777
811
  # Test credentials (for integration tests)
778
812
  API_URL=https://api.das-dev.nioz.nl
779
813
  USER_NAME=
@@ -787,6 +821,8 @@ OPEN_AI_MODEL_ID=gpt-4o-mini
787
821
  - `DAS_API_URL`: default API URL for app/managers when no explicit URL is provided.
788
822
  - `DAS_API_KEY`: API key auth (takes precedence over stored token in auth layer).
789
823
  - `VERIFY_SSL`: TLS verification (`True`/`False`).
824
+ - `DAS_LOG_LEVEL`: diagnostic log level (`TRACE`/`DEBUG`/`INFO`/`WARN`/`ERROR`/`FATAL`); overrides `das config log-level`.
825
+ - `DAS_LOG_FILE`: path to also write logs to a file; overrides `das config log-file`.
790
826
  - `API_URL`, `USER_NAME`, `USER_PASSWORD`: used by integration tests.
791
827
 
792
828
  ## Unit Tests and Integration Tests
@@ -820,6 +856,10 @@ The tests are a good source of realistic payload examples, especially:
820
856
  - prefer double quotes around query arguments containing `*`, `;`, and parentheses.
821
857
  - No API URL configured:
822
858
  - set `DAS_API_URL`, pass URL to `Das(...)`, or run `das login --api-url ...`.
859
+ - Need more detail on any error:
860
+ - raise verbosity with `das config log-level DEBUG` (optionally
861
+ `das config log-file <path>`) to see the full HTTP requests and error
862
+ details. See [Logging](#logging).
823
863
 
824
864
  ## Contributing
825
865
 
@@ -56,6 +56,7 @@ das entry get --code zb.b.1ub
56
56
  - [Digital Objects](#digital-objects)
57
57
  - [Downloads](#downloads)
58
58
  - [Other CLI groups](#other-cli-groups)
59
+ - [Logging](#logging)
59
60
 
60
61
  ### Authentication
61
62
 
@@ -191,8 +192,37 @@ das config ssl-verify true
191
192
  das config ssl-status
192
193
  das config show
193
194
  das config reset --force
195
+
196
+ # Logging
197
+ das config log-level DEBUG # TRACE, DEBUG, INFO, WARN (default), ERROR, FATAL
198
+ das config log-file C:\logs\das.log # also write logs to a file
199
+ das config log-file --clear # back to console only
194
200
  ```
195
201
 
202
+ #### Logging
203
+
204
+ The CLI logs diagnostics (HTTP requests and error details) through the `das`
205
+ logger. Control how much is shown and where it goes:
206
+
207
+ - **Level** — from most to least verbose: `TRACE`, `DEBUG`, `INFO`, `WARN`
208
+ (default), `ERROR`, `FATAL`. Set with `das config log-level <LEVEL>` or the
209
+ `DAS_LOG_LEVEL` environment variable.
210
+ - **Destination** — logs go to the console by default. Also write them to a file
211
+ with `das config log-file <path>` (parent folders are created automatically)
212
+ or the `DAS_LOG_FILE` environment variable; use `das config log-file --clear`
213
+ to go back to console-only. The file log includes timestamps and logger names
214
+ while the console stays terse.
215
+
216
+ ```bash
217
+ # Verbose troubleshooting session written to a file
218
+ das config log-level DEBUG
219
+ das config log-file C:\logs\das.log
220
+ das search entries --attribute Cruise --query "cruisecode(*64PE*)"
221
+ ```
222
+
223
+ > Tip: this is the diagnostic log for the CLI itself. For an entry's
224
+ > change/audit history, use [`das entry logs`](#logs-and-ownership) instead.
225
+
196
226
  ## Programmatic Usage (Python)
197
227
 
198
228
  Two common patterns are supported.
@@ -751,6 +781,10 @@ DAS_API_URL=https://api.das-dev.nioz.nl
751
781
  DAS_API_KEY=
752
782
  VERIFY_SSL=True
753
783
 
784
+ # Logging
785
+ DAS_LOG_LEVEL=WARN
786
+ DAS_LOG_FILE=
787
+
754
788
  # Test credentials (for integration tests)
755
789
  API_URL=https://api.das-dev.nioz.nl
756
790
  USER_NAME=
@@ -764,6 +798,8 @@ OPEN_AI_MODEL_ID=gpt-4o-mini
764
798
  - `DAS_API_URL`: default API URL for app/managers when no explicit URL is provided.
765
799
  - `DAS_API_KEY`: API key auth (takes precedence over stored token in auth layer).
766
800
  - `VERIFY_SSL`: TLS verification (`True`/`False`).
801
+ - `DAS_LOG_LEVEL`: diagnostic log level (`TRACE`/`DEBUG`/`INFO`/`WARN`/`ERROR`/`FATAL`); overrides `das config log-level`.
802
+ - `DAS_LOG_FILE`: path to also write logs to a file; overrides `das config log-file`.
767
803
  - `API_URL`, `USER_NAME`, `USER_PASSWORD`: used by integration tests.
768
804
 
769
805
  ## Unit Tests and Integration Tests
@@ -797,6 +833,10 @@ The tests are a good source of realistic payload examples, especially:
797
833
  - prefer double quotes around query arguments containing `*`, `;`, and parentheses.
798
834
  - No API URL configured:
799
835
  - set `DAS_API_URL`, pass URL to `Das(...)`, or run `das login --api-url ...`.
836
+ - Need more detail on any error:
837
+ - raise verbosity with `das config log-level DEBUG` (optionally
838
+ `das config log-file <path>`) to see the full HTTP requests and error
839
+ details. See [Logging](#logging).
800
840
 
801
841
  ## Contributing
802
842
 
@@ -807,4 +847,4 @@ For bugs or feature requests, use the project issue tracker:
807
847
 
808
848
  ## License
809
849
 
810
- MIT License
850
+ MIT License
@@ -1,5 +1,6 @@
1
1
  from das.common.api import post_data
2
2
  from das.common.config import save_token
3
+ from das.common.errors import extract_api_error
3
4
 
4
5
 
5
6
  class Auth:
@@ -15,9 +16,18 @@ class Auth:
15
16
  def authenticate(self, password):
16
17
  """
17
18
  Authenticate the user and obtain an access token.
18
-
19
+
19
20
  Args:
20
21
  password (str): The password to authenticate with
22
+
23
+ Returns:
24
+ str: The access token on success.
25
+
26
+ Raises:
27
+ ValueError: With a descriptive message when authentication fails —
28
+ distinguishing bad credentials (the API's message) from
29
+ connection-level problems such as an untrusted TLS certificate
30
+ or an unreachable host.
21
31
  """
22
32
  url = f"{self.base_url}/api/TokenAuth/Authenticate"
23
33
  data = {
@@ -25,14 +35,22 @@ class Auth:
25
35
  "password": password
26
36
  }
27
37
  response = post_data(url, data=data)
28
- if response.get("error"):
29
- print(f"Authentication failed: {response['error']}")
30
- else:
31
- self.token = response.get("result").get("accessToken")
38
+
39
+ if not isinstance(response, dict):
40
+ raise ValueError("Unexpected response from the authentication endpoint.")
41
+
42
+ result = response.get("result") if response.get("success") is True else None
43
+ token = result.get("accessToken") if isinstance(result, dict) else None
44
+
45
+ if token:
46
+ self.token = token
32
47
  save_token(self.token)
33
48
  # Return silently, let the CLI handle success messages
34
49
  return self.token
35
50
 
51
+ # Failure: surface the real reason (API message, SSL/cert or connection error).
52
+ raise ValueError(extract_api_error(response, "Authentication failed."))
53
+
36
54
  if __name__ == "__main__":
37
55
  # Example for testing authentication
38
56
  import getpass
@@ -9,8 +9,10 @@ from das.common.config import (
9
9
  load_openai_api_key, save_openai_api_key, clear_openai_api_key,
10
10
  clear_token, _config_dir,
11
11
  save_oauth_config, load_oauth_config, get_auth_type, set_auth_type,
12
- save_token, save_token_expiry, save_refresh_token, clear_refresh_token
12
+ save_token, save_token_expiry, save_refresh_token, clear_refresh_token,
13
+ save_log_level, load_log_level, save_log_file, load_log_file, configure_logging,
13
14
  )
15
+ from das.common.enums import LogLevel
14
16
 
15
17
  from das.app import Das
16
18
  from das.managers.download_manager import DownloadManager
@@ -166,8 +168,13 @@ def login(das_ctx, api_url, username, password, use_oauth, api_key, debug):
166
168
  if not password:
167
169
  password = click.prompt("Password", hide_input=True)
168
170
 
169
- client = das_ctx.get_client()
170
- token = client.authenticate(username, password)
171
+ try:
172
+ client = das_ctx.get_client()
173
+ token = client.authenticate(username, password)
174
+ except Exception as e:
175
+ click.secho(f"❌ Authentication failed: {e}", fg="red")
176
+ return
177
+
171
178
  if not token:
172
179
  click.secho("❌ Authentication failed. Please check your credentials.", fg="red")
173
180
  return
@@ -273,7 +280,8 @@ def search_help():
273
280
  click.echo(" --max-results <n> Number of results per page (default: 10)")
274
281
 
275
282
  click.secho("\nSorting:", fg="blue", bold=True)
276
- click.echo(" --sort-by <field> Field to sort by (default: Name)")
283
+ click.echo(" --sort-by <field> Field to sort by (default: none — the server decides the order)")
284
+ click.echo(" Note: not every attribute has a 'Name' field (e.g. Cruise).")
277
285
  click.echo(" --sort-order <order> Sort order: 'asc' or 'desc' (default: asc)")
278
286
  click.echo("\n")
279
287
 
@@ -282,7 +290,7 @@ def search_help():
282
290
  @click.option('--query', required=True, help='Search query string')
283
291
  @click.option('--max-results', default=10, help='Maximum number of results to return')
284
292
  @click.option('--page', default=1, help='Page number for paginated results')
285
- @click.option('--sort-by', default='Name', help='Field to sort by (default: Name)')
293
+ @click.option('--sort-by', default='', help='Field to sort by (default: none — the server decides the order)')
286
294
  @click.option('--sort-order', default='asc', type=click.Choice(['asc', 'desc']), help='Sort order (asc or desc)')
287
295
  @click.option('--format', 'output_format', default='table', type=click.Choice(['table', 'json', 'compact']), help='Output format (table, json, or compact)')
288
296
  @click.option('--raw', is_flag=True, help='Show raw response from API')
@@ -1141,6 +1149,48 @@ def get_ssl_status():
1141
1149
  status = "enabled" if VERIFY_SSL else "disabled"
1142
1150
  click.echo(f"SSL certificate verification is currently {status}")
1143
1151
 
1152
+ @config.command("log-level")
1153
+ @click.argument('level', type=click.Choice([l.name for l in LogLevel], case_sensitive=False), required=True)
1154
+ def set_log_level(level):
1155
+ """Set the diagnostic log level.
1156
+
1157
+ Levels (most to least verbose): TRACE, DEBUG, INFO, WARN, ERROR, FATAL.
1158
+
1159
+ \b
1160
+ Example:
1161
+ das config log-level DEBUG
1162
+ """
1163
+ save_log_level(level)
1164
+ configure_logging()
1165
+ click.secho(f"✓ Log level set to {level.upper()}", fg="green")
1166
+
1167
+ @config.command("log-file")
1168
+ @click.argument('path', required=False)
1169
+ @click.option('--clear', 'clear_path', is_flag=True, help='Stop writing logs to a file (console only)')
1170
+ def set_log_file(path, clear_path):
1171
+ """Set (or clear) the file logs are written to.
1172
+
1173
+ \b
1174
+ Examples:
1175
+ # Write logs to a file
1176
+ das config log-file C:\\logs\\das.log
1177
+
1178
+ \b
1179
+ # Log to the console only
1180
+ das config log-file --clear
1181
+ """
1182
+ if clear_path:
1183
+ save_log_file(None)
1184
+ configure_logging()
1185
+ click.secho("✓ File logging disabled (console only).", fg="green")
1186
+ return
1187
+ if not path:
1188
+ raise click.UsageError("Provide a file path, or use --clear to disable file logging.")
1189
+ save_log_file(path)
1190
+ configure_logging()
1191
+ resolved = load_log_file()
1192
+ click.secho(f"✓ Logs will be written to: {resolved}", fg="green")
1193
+
1144
1194
  @config.command("show")
1145
1195
  def config_show():
1146
1196
  """Show all current persistent settings"""
@@ -1168,10 +1218,19 @@ def config_show():
1168
1218
  click.secho("Current settings", bold=True)
1169
1219
  click.echo("─" * 40)
1170
1220
 
1221
+ # Logging
1222
+ log_level = load_log_level().name
1223
+ log_file = load_log_file() or "(console only)"
1224
+
1171
1225
  click.secho(" Connection", fg="blue", bold=True)
1172
1226
  click.echo(f" API URL : {api_url}")
1173
1227
  click.echo(f" SSL verify : {'enabled' if ssl else 'disabled'}")
1174
1228
 
1229
+ click.echo("")
1230
+ click.secho(" Logging", fg="blue", bold=True)
1231
+ click.echo(f" Log level : {log_level}")
1232
+ click.echo(f" Log file : {log_file}")
1233
+
1175
1234
  click.echo("")
1176
1235
  click.secho(" Authentication", fg="blue", bold=True)
1177
1236
  click.echo(f" Auth type : {auth_type}")
@@ -0,0 +1,177 @@
1
+ import json
2
+ import logging
3
+ import requests
4
+ from das.common.config import load_verify_ssl
5
+ from das.common.errors import describe_request_exception
6
+
7
+ logger = logging.getLogger("das")
8
+
9
+ # Default network timeout (connect, read) in seconds. Prevents the CLI from
10
+ # hanging indefinitely on an unreachable host.
11
+ DEFAULT_TIMEOUT = (10, 60)
12
+
13
+
14
+ def _process_response(response, action: str):
15
+ """Turn a ``requests.Response`` into a parsed dict or a structured error dict.
16
+
17
+ On a successful JSON parse the body is returned as-is (so ABP envelopes with
18
+ ``success``/``error`` flow through to the services). When the HTTP status is
19
+ an error the status code is attached so callers can build a descriptive
20
+ message. A non-JSON body is reported with its status code and a snippet.
21
+ """
22
+ # ``status_code`` is the authoritative error signal; ``response.ok`` is a
23
+ # derived convenience flag (``status_code < 400``). Prefer the former so the
24
+ # behaviour does not depend on ``.ok`` being populated.
25
+ is_http_error = response.status_code >= 400
26
+
27
+ try:
28
+ data = response.json()
29
+ except json.JSONDecodeError as json_err:
30
+ # Not JSON. If the status is an error, surface that clearly.
31
+ if is_http_error:
32
+ message = (
33
+ f"The server returned HTTP {response.status_code} "
34
+ f"({response.reason}) while trying to {action}."
35
+ )
36
+ logger.error("%s Response body: %s", message, response.text[:500])
37
+ return {
38
+ "error": message,
39
+ "status_code": response.status_code,
40
+ "raw_content": response.text[:500],
41
+ }
42
+ logger.error("Error decoding JSON response: %s", json_err)
43
+ return {
44
+ "error": f"Invalid JSON response: {json_err}",
45
+ "status_code": response.status_code,
46
+ "raw_content": response.text[:500],
47
+ }
48
+
49
+ if isinstance(data, dict) and is_http_error:
50
+ # ABP usually returns 200 even for logical errors, but when the HTTP
51
+ # status itself is an error make sure the code travels with the body.
52
+ data.setdefault("status_code", response.status_code)
53
+ logger.debug(
54
+ "%s returned HTTP %s: %s", action, response.status_code, data.get("error")
55
+ )
56
+ return data
57
+
58
+
59
+ def get_data(url, headers=None, params=None):
60
+ """
61
+ Fetch data from a REST API endpoint.
62
+
63
+ Args:
64
+ url (str): The API endpoint URL.
65
+ headers (dict, optional): Headers to include in the request.
66
+ params (dict, optional): Query parameters for the request.
67
+
68
+ Returns:
69
+ dict: The JSON response from the API or an error message.
70
+ """
71
+ logger.debug("GET %s", url)
72
+ try:
73
+ response = requests.get(
74
+ url, headers=headers, params=params,
75
+ verify=load_verify_ssl(), timeout=DEFAULT_TIMEOUT,
76
+ )
77
+ return _process_response(response, "fetch data")
78
+ except requests.RequestException as e:
79
+ message = describe_request_exception(e, url)
80
+ logger.error("Error fetching API data: %s", message)
81
+ return {"error": message}
82
+
83
+ def get_binary_response(url, headers=None, params=None, stream=True):
84
+ """
85
+ Perform a GET request expected to return binary content.
86
+
87
+ Returns the raw requests.Response so callers can inspect headers
88
+ and stream content to disk.
89
+ """
90
+ logger.debug("GET (binary) %s", url)
91
+ try:
92
+ response = requests.get(
93
+ url,
94
+ headers=headers,
95
+ params=params,
96
+ verify=load_verify_ssl(),
97
+ stream=stream,
98
+ timeout=DEFAULT_TIMEOUT,
99
+ )
100
+ response.raise_for_status()
101
+ return response
102
+ except requests.RequestException as e:
103
+ message = describe_request_exception(e, url)
104
+ logger.error("Error fetching binary API data: %s", message)
105
+ return {"error": message}
106
+
107
+ def post_data(url, headers=None, data=None):
108
+ """
109
+ Send data to a REST API endpoint.
110
+
111
+ Args:
112
+ url (str): The API endpoint URL.
113
+ headers (dict, optional): Headers to include in the request.
114
+ data (dict, optional): The data to send in the request body.
115
+
116
+ Returns:
117
+ dict: The JSON response from the API or an error message.
118
+ """
119
+ logger.debug("POST %s", url)
120
+ try:
121
+ response = requests.post(
122
+ url, headers=headers, json=data,
123
+ verify=load_verify_ssl(), timeout=DEFAULT_TIMEOUT,
124
+ )
125
+ return _process_response(response, "post data")
126
+ except requests.RequestException as e:
127
+ message = describe_request_exception(e, url)
128
+ logger.error("Error posting API data: %s", message)
129
+ return {"error": message}
130
+
131
+ def put_data(url, headers=None, data=None):
132
+ """
133
+ Update data at a REST API endpoint.
134
+
135
+ Args:
136
+ url (str): The API endpoint URL.
137
+ headers (dict, optional): Headers to include in the request.
138
+ data (dict, optional): The data to send in the request body.
139
+
140
+ Returns:
141
+ dict: The JSON response from the API or an error message.
142
+ """
143
+ logger.debug("PUT %s", url)
144
+ try:
145
+ response = requests.put(
146
+ url, headers=headers, json=data,
147
+ verify=load_verify_ssl(), timeout=DEFAULT_TIMEOUT,
148
+ )
149
+ return _process_response(response, "update data")
150
+ except requests.RequestException as e:
151
+ message = describe_request_exception(e, url)
152
+ logger.error("Error updating API data: %s", message)
153
+ return {"error": message}
154
+
155
+ def delete_data(url, headers=None, data=None):
156
+ """
157
+ Delete data from a REST API endpoint.
158
+
159
+ Args:
160
+ url (str): The API endpoint URL.
161
+ headers (dict, optional): Headers to include in the request.
162
+ data (dict, optional): The data to send in the request body.
163
+
164
+ Returns:
165
+ dict: The JSON response from the API or an error message.
166
+ """
167
+ logger.debug("DELETE %s", url)
168
+ try:
169
+ response = requests.delete(
170
+ url, headers=headers, json=data,
171
+ verify=load_verify_ssl(), timeout=DEFAULT_TIMEOUT,
172
+ )
173
+ return _process_response(response, "delete data")
174
+ except requests.RequestException as e:
175
+ message = describe_request_exception(e, url)
176
+ logger.error("Error deleting API data: %s", message)
177
+ return {"error": message}