AAS HTTP Client Documentation
Loading...
Searching...
No Matches
experimental_implementation.py
Go to the documentation of this file.
1"""Experimental implementation of Asset Administration Shell Registry related API calls."""
2
3import json
4import logging
5import mimetypes
6from pathlib import Path
7from typing import TYPE_CHECKING, Any
8
9from aas_http_client.utilities.constants import LogIntensity
10
11if TYPE_CHECKING:
12 from aas_http_client.classes.client.aas_client import AasHttpClient
13
14import requests
15from pydantic import BaseModel
16
17from aas_http_client.utilities.encoder import encode_base_64
19 STATUS_CODE_200,
20 STATUS_CODE_201,
21 STATUS_CODE_204,
22 STATUS_CODE_404,
23 log_response,
24)
25
26_logger = logging.getLogger(__name__)
27
28
30 """Implementation of Asset Administration Shell Registry related API calls."""
31
32 def __init__(self, client: "AasHttpClient"):
33 """Initializes the ExperimentalImplementation with the given client."""
34 self._client = client
35
36 session = client.get_session()
37 if session is None:
38 raise ValueError(
39 "HTTP session is not initialized in the client. Call 'initialize()' method of the client before creating ExperimentalImplementation instance."
40 )
41
42 self._session: requests.Session = session
43
44 # GET /concept-descriptions
46 self, id_short: str = "", is_case_of: str = "", data_specification_ref: str = "", limit: int = 100, cursor: str = ""
47 ):
48 """Retrieves concept descriptions. Experimental feature - may not be supported by all servers.
49
50 :param id_short: Filter by idShort
51 :param is_case_of: Filter by isCaseOf
52 :param data_specification_ref: Filter by dataSpecificationRef
53 :param limit: Maximum number of results to return
54 :param cursor: Cursor for pagination
55 :return: List of concept descriptions as dictionaries or None if an error occurs
56 """
57 url = f"{self._client.base_url}/concept-descriptions"
58
59 # Build query parameters
60
61 params: dict[str, Any] = {}
62 if id_short:
63 params["idShort"] = id_short
64 if is_case_of:
65 params["isCaseOf"] = is_case_of
66 if data_specification_ref:
67 params["dataSpecificationRef"] = data_specification_ref
68 if limit:
69 params["limit"] = str(limit)
70 if cursor:
71 params["cursor"] = cursor
72
73 self._client.set_token() # ensures Authorization header is set
74
75 try:
76 response = self._session.get(url, timeout=self._client.time_out, params=params)
77 _logger.debug(f"Call REST API url '{response.url}'")
78
79 if response.status_code != STATUS_CODE_200:
80 log_response(response)
81 return None
82
83 except requests.exceptions.RequestException as e:
84 _logger.error(f"Error call REST API: {e}")
85 return None
86
87 content = response.content.decode("utf-8")
88 return json.loads(content)
89
90 # GET /concept-descriptions/{conceptDescriptionIdentifier}
91 def get_concept_description_by_id(self, concept_description_identifier: str):
92 """Retrieves a specific concept description by its identifier. Experimental feature - may not be supported by all servers.
93
94 :param concept_description_identifier: The unique identifier of the concept description
95 :return: Concept description data as a dictionary or None if not found
96 """
97 url = f"{self._client.base_url}/concept-descriptions/{concept_description_identifier}"
98
99 self._client.set_token() # ensures Authorization header is set
100
101 try:
102 response = self._session.get(url, timeout=self._client.time_out)
103 _logger.debug(f"Call REST API url '{response.url}'")
104
105 if response.status_code == STATUS_CODE_404:
106 if self._client.get_log_intensity() == LogIntensity.HIGH:
107 _logger.warning(f"Concept description with id '{concept_description_identifier}' not found.")
108 elif self._client.get_log_intensity() == LogIntensity.STANDARD:
109 _logger.debug(f"Concept description with id '{concept_description_identifier}' not found.")
110
111 return None
112
113 if response.status_code != STATUS_CODE_200:
114 log_response(response)
115 return None
116
117 except requests.exceptions.RequestException as e:
118 _logger.error(f"Error calling REST API: {e}")
119 return None
120
121 return response.json()
122
123 # POST /concept-descriptions
124 def post_concept_description(self, concept_description: dict) -> bool:
125 """Creates a new concept description. Experimental feature - may not be supported by all servers.
126
127 :param concept_description: Concept description data as a dictionary
128 :return: True if creation was successful, False otherwise
129 """
130 url = f"{self._client.base_url}/concept-descriptions"
131
132 self._client.set_token() # ensures Authorization header is set
133
134 try:
135 response = self._session.post(url, json=concept_description, timeout=self._client.time_out)
136 _logger.debug(f"Call REST API url '{response.url}'")
137
138 if response.status_code == STATUS_CODE_404:
139 if self._client.get_log_intensity() == LogIntensity.HIGH:
140 _logger.warning("Concept descriptions endpoint not found.")
141 elif self._client.get_log_intensity() == LogIntensity.STANDARD:
142 _logger.debug("Concept descriptions endpoint not found.")
143
144 return False
145
146 if response.status_code != STATUS_CODE_201:
147 log_response(response)
148 return False
149
150 except requests.exceptions.RequestException as e:
151 _logger.error(f"Error calling REST API: {e}")
152 return False
153
154 return True
155
156 # DELETE /concept-descriptions/{conceptDescriptionIdentifier}
157 def delete_concept_description_by_id(self, concept_description_identifier: str) -> bool:
158 """Deletes a specific concept description by its identifier. Experimental feature - may not be supported by all servers.
159
160 :param concept_description_identifier: The unique identifier of the concept description
161 :return: True if deletion was successful, False otherwise
162 """
163 url = f"{self._client.base_url}/concept-descriptions/{concept_description_identifier}"
164
165 self._client.set_token() # ensures Authorization header is set
166
167 try:
168 response = self._session.delete(url, timeout=self._client.time_out)
169 _logger.debug(f"Call REST API url '{response.url}'")
170
171 if response.status_code == STATUS_CODE_404:
172 if self._client.get_log_intensity() == LogIntensity.HIGH:
173 _logger.warning(f"Concept description with id '{concept_description_identifier}' not found.")
174 elif self._client.get_log_intensity() == LogIntensity.STANDARD:
175 _logger.debug(f"Concept description with id '{concept_description_identifier}' not found.")
176
177 return False
178
179 if response.status_code != STATUS_CODE_204:
180 log_response(response)
181 return False
182
183 except requests.exceptions.RequestException as e:
184 _logger.error(f"Error calling REST API: {e}")
185 return False
186
187 return True
188
189 # GET /submodels/{submodelIdentifier}/submodel-elements/{idShortPath}/attachment
190 def get_file_by_path_submodel_repo(self, submodel_identifier: str, id_short_path: str) -> bytes | None:
191 """Downloads file content from a specific submodel element from the Submodel at a specified path. Experimental feature - may not be supported by all servers.
192
193 :param submodel_identifier: The Submodels unique id
194 :param id_short_path: IdShort path to the submodel element (dot-separated)
195 :return: Attachment file data as bytes (octet-stream) or None if an error occurred
196 """
197 if not self._client.encoded_ids:
198 submodel_identifier = encode_base_64(submodel_identifier)
200 url = f"{self._client.base_url}/submodels/{submodel_identifier}/submodel-elements/{id_short_path}/attachment"
201
202 self._client.set_token() # ensures Authorization header is set
203
204 try:
205 response = self._session.get(url, timeout=self._client.time_out)
206 _logger.debug(f"Call REST API url '{response.url}'")
207
208 if response.status_code == STATUS_CODE_404:
209 if self._client.get_log_intensity() == LogIntensity.HIGH:
210 _logger.warning(
211 f"Submodel with id '{submodel_identifier}' or Submodel element with IDShort path '{id_short_path}' or file content not found."
212 )
213 elif self._client.get_log_intensity() == LogIntensity.STANDARD:
214 _logger.debug(
215 f"Submodel with id '{submodel_identifier}' or Submodel element with IDShort path '{id_short_path}' or file content not found."
216 )
217
218 return None
219
220 if response.status_code != STATUS_CODE_200:
221 log_response(response)
222 return None
223
224 except requests.exceptions.RequestException as e:
225 _logger.error(f"Error calling REST API: {e}")
226 return None
227
228 return response.content
229
230 # POST /submodels/{submodelIdentifier}/submodel-elements/{idShortPath}/attachment
231 def post_file_by_path_submodel_repo(self, submodel_identifier: str, id_short_path: str, file: Path) -> bool:
232 """Uploads file content to an existing submodel element at a specified path within submodel elements hierarchy. Experimental feature - may not be supported by all servers.
233
234 :param submodel_identifier: The Submodels unique id
235 :param id_short_path: IdShort path to the submodel element (dot-separated)
236 :param file: Path to the file to upload as attachment
237 :return: Attachment data as bytes or None if an error occurred
238 """
239 if file.exists() is False or not file.is_file():
240 _logger.error(f"Attachment file '{file}' does not exist.")
241 return False
242
243 if not self._client.encoded_ids:
244 submodel_identifier = encode_base_64(submodel_identifier)
245
246 url = f"{self._client.base_url}/submodels/{submodel_identifier}/submodel-elements/{id_short_path}/attachment"
247
248 self._client.set_token()
249
250 try:
251 mime_type, _ = mimetypes.guess_type(file)
252
253 with file.open("rb") as f:
254 files = {"file": (file.name, f, mime_type or "application/octet-stream")}
255 response = self._session.post(url, files=files, timeout=self._client.time_out)
256
257 _logger.debug(f"Call REST API url '{response.url}'")
258
259 if response.status_code == STATUS_CODE_404:
260 if self._client.get_log_intensity() == LogIntensity.HIGH:
261 _logger.warning(f"Submodel with id '{submodel_identifier}' or Submodel element with IDShort path '{id_short_path}' not found.")
262 elif self._client.get_log_intensity() == LogIntensity.STANDARD:
263 _logger.debug(f"Submodel with id '{submodel_identifier}' or Submodel element with IDShort path '{id_short_path}' not found.")
264
265 return False
266
267 # original dotnet server delivers 200 instead of 204
268 if response.status_code not in (STATUS_CODE_200, STATUS_CODE_204):
269 log_response(response)
270 return False
271
272 except requests.exceptions.RequestException as e:
273 _logger.error(f"Error call REST API: {e}")
274 return False
275
276 return True
277
278 # POST /submodels/{submodelIdentifier}/submodel-elements/{idShortPath}/attachment
280 self, submodel_identifier: str, id_short_path: str, file_octet_stream: Any, mime_type: str = "application/octet-stream"
281 ) -> bool:
282 """Uploads file content to an existing submodel element at a specified path within submodel elements hierarchy. Experimental feature - may not be supported by all servers.
283
284 :param submodel_identifier: The Submodels unique id
285 :param id_short_path: IdShort path to the submodel element (dot-separated)
286 :param file_octet_stream: File content as a byte stream
287 :return: Attachment data as bytes or None if an error occurred
288 """
289 if file_octet_stream is None:
290 _logger.error("Attachment file stream is None.")
291 return False
292
293 if not self._client.encoded_ids:
294 submodel_identifier = encode_base_64(submodel_identifier)
295
296 url = f"{self._client.base_url}/submodels/{submodel_identifier}/submodel-elements/{id_short_path}/attachment"
297
298 self._client.set_token()
299
300 try:
301 files = {"file": ("attachment", file_octet_stream, mime_type or "application/octet-stream")}
302 response = self._session.post(url, files=files, timeout=self._client.time_out)
303
304 _logger.debug(f"Call REST API url '{response.url}'")
305
306 if response.status_code == STATUS_CODE_404:
307 if self._client.get_log_intensity() == LogIntensity.HIGH:
308 _logger.warning(f"Submodel with id '{submodel_identifier}' or Submodel element with IDShort path '{id_short_path}' not found.")
309 elif self._client.get_log_intensity() == LogIntensity.STANDARD:
310 _logger.debug(f"Submodel with id '{submodel_identifier}' or Submodel element with IDShort path '{id_short_path}' not found.")
311
312 return False
313
314 # original dotnet server delivers 200 instead of 204
315 if response.status_code not in (STATUS_CODE_200, STATUS_CODE_204):
316 log_response(response)
317 return False
318
319 except requests.exceptions.RequestException as e:
320 _logger.error(f"Error call REST API: {e}")
321 return False
322
323 return True
324
325 # PUT /submodels/{submodelIdentifier}/submodel-elements/{idShortPath}/attachment
326 def put_file_by_path_submodel_repo(self, submodel_identifier: str, id_short_path: str, file: Path) -> bool:
327 """Uploads file content to an existing submodel element at a specified path within submodel elements hierarchy. Experimental feature - may not be supported by all servers.
328
329 :param submodel_identifier: The Submodels unique id
330 :param id_short_path: IdShort path to the submodel element (dot-separated)
331 :param file: Path to the file to upload as attachment
332 :return: Attachment data as bytes or None if an error occurred
333 """
334 if file.exists() is False or not file.is_file():
335 _logger.error(f"Attachment file '{file}' does not exist.")
336 return False
337
338 if not self._client.encoded_ids:
339 submodel_identifier = encode_base_64(submodel_identifier)
340
341 url = f"{self._client.base_url}/submodels/{submodel_identifier}/submodel-elements/{id_short_path}/attachment"
342
343 self._client.set_token()
344
345 try:
346 mime_type, _ = mimetypes.guess_type(file)
347
348 with file.open("rb") as f:
349 files = {"file": (file.name, f, mime_type or "application/octet-stream")}
350 response = self._session.put(url, files=files, timeout=self._client.time_out)
351
352 _logger.debug(f"Call REST API url '{response.url}'")
353
354 if response.status_code == STATUS_CODE_404:
355 if self._client.get_log_intensity() == LogIntensity.HIGH:
356 _logger.warning(f"Submodel with id '{submodel_identifier}' or Submodel element with IDShort path '{id_short_path}' not found.")
357 elif self._client.get_log_intensity() == LogIntensity.STANDARD:
358 _logger.debug(f"Submodel with id '{submodel_identifier}' or Submodel element with IDShort path '{id_short_path}' not found.")
359
360 return False
361
362 # original dotnet server delivers 200 instead of 204
363 if response.status_code not in (STATUS_CODE_200, STATUS_CODE_204):
364 log_response(response)
365 return False
366
367 except requests.exceptions.RequestException as e:
368 _logger.error(f"Error call REST API: {e}")
369 return False
370
371 return True
372
373 # PUT /submodels/{submodelIdentifier}/submodel-elements/{idShortPath}/attachment
375 self, submodel_identifier: str, id_short_path: str, file_octet_stream: Any, mime_type: str = "application/octet-stream"
376 ) -> bool:
377 """Uploads file content to an existing submodel element at a specified path within submodel elements hierarchy. Experimental feature - may not be supported by all servers.
378
379 :param submodel_identifier: The Submodels unique id
380 :param id_short_path: IdShort path to the submodel element (dot-separated)
381 :param file_octet_stream: File content as a byte stream
382 :return: Attachment data as bytes or None if an error occurred
383 """
384 if file_octet_stream is None:
385 _logger.error("Attachment file stream is None.")
386 return False
387
388 if not self._client.encoded_ids:
389 submodel_identifier = encode_base_64(submodel_identifier)
390
391 url = f"{self._client.base_url}/submodels/{submodel_identifier}/submodel-elements/{id_short_path}/attachment"
392
393 self._client.set_token()
394
395 try:
396 files = {"file": ("attachment", file_octet_stream, mime_type or "application/octet-stream")}
397 response = self._session.put(url, files=files, timeout=self._client.time_out)
398
399 _logger.debug(f"Call REST API url '{response.url}'")
400
401 if response.status_code == STATUS_CODE_404:
402 if self._client.get_log_intensity() == LogIntensity.HIGH:
403 _logger.warning(f"Submodel with id '{submodel_identifier}' or Submodel element with IDShort path '{id_short_path}' not found.")
404 elif self._client.get_log_intensity() == LogIntensity.STANDARD:
405 _logger.debug(f"Submodel with id '{submodel_identifier}' or Submodel element with IDShort path '{id_short_path}' not found.")
406
407 return False
408
409 # original dotnet server delivers 200 instead of 204
410 if response.status_code not in (STATUS_CODE_200, STATUS_CODE_204):
411 log_response(response)
412 return False
413
414 except requests.exceptions.RequestException as e:
415 _logger.error(f"Error call REST API: {e}")
416 return False
417
418 return True
419
420 # DELETE /submodels/{submodelIdentifier}/submodel-elements/{idShortPath}/attachment
421 def delete_file_by_path_submodel_repo(self, submodel_identifier: str, id_short_path: str) -> bool:
422 """Deletes file content of an existing submodel element at a specified path within submodel elements hierarchy. Experimental feature - may not be supported by all servers.
423
424 :param submodel_identifier: The Submodels unique id
425 :param id_short_path: IdShort path to the submodel element (dot-separated)
426 :return: True if deletion was successful, False otherwise
427 """
428 if not self._client.encoded_ids:
429 submodel_identifier = encode_base_64(submodel_identifier)
431 url = f"{self._client.base_url}/submodels/{submodel_identifier}/submodel-elements/{id_short_path}/attachment"
432
433 self._client.set_token()
434
435 try:
436 response = self._session.delete(url, timeout=self._client.time_out)
437 _logger.debug(f"Call REST API url '{response.url}'")
438
439 if response.status_code == 404:
440 if self._client.get_log_intensity() == LogIntensity.HIGH:
441 _logger.warning(f"Submodel with id '{submodel_identifier}' or Submodel element with IDShort path '{id_short_path}' not found.")
442 elif self._client.get_log_intensity() == LogIntensity.STANDARD:
443 _logger.debug(f"Submodel with id '{submodel_identifier}' or Submodel element with IDShort path '{id_short_path}' not found.")
444
445 return False
446
447 if response.status_code != STATUS_CODE_200:
448 log_response(response)
449 return False
450
451 except requests.exceptions.RequestException as e:
452 _logger.error(f"Error calling REST API: {e}")
453 return False
454
455 return True
456
457 def __post_multipart(self, url, files) -> requests.Response:
458 headers = dict(self._session.headers)
459 headers.pop("Content-Type", None)
460 return self._session.post(url, headers=headers, files=files)
Implementation of Asset Administration Shell Registry related API calls.
bool delete_file_by_path_submodel_repo(self, str submodel_identifier, str id_short_path)
Deletes file content of an existing submodel element at a specified path within submodel elements hie...
bool post_file_by_path_submodel_repo(self, str submodel_identifier, str id_short_path, Path file)
Uploads file content to an existing submodel element at a specified path within submodel elements hie...
bool post_file_by_path_submodel_repo_stream(self, str submodel_identifier, str id_short_path, Any file_octet_stream, str mime_type="application/octet-stream")
Uploads file content to an existing submodel element at a specified path within submodel elements hie...
bytes|None get_file_by_path_submodel_repo(self, str submodel_identifier, str id_short_path)
Downloads file content from a specific submodel element from the Submodel at a specified path.
get_concept_description_by_id(self, str concept_description_identifier)
Retrieves a specific concept description by its identifier.
bool put_file_by_path_submodel_repo_stream(self, str submodel_identifier, str id_short_path, Any file_octet_stream, str mime_type="application/octet-stream")
Uploads file content to an existing submodel element at a specified path within submodel elements hie...
bool post_concept_description(self, dict concept_description)
Creates a new concept description.
__init__(self, "AasHttpClient" client)
Initializes the ExperimentalImplementation with the given client.
bool put_file_by_path_submodel_repo(self, str submodel_identifier, str id_short_path, Path file)
Uploads file content to an existing submodel element at a specified path within submodel elements hie...
get_concept_descriptions(self, str id_short="", str is_case_of="", str data_specification_ref="", int limit=100, str cursor="")
Retrieves concept descriptions.
bool delete_concept_description_by_id(self, str concept_description_identifier)
Deletes a specific concept description by its identifier.