entryscape 1.3.0__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 (82) hide show
  1. entryscape/__init__.py +219 -0
  2. entryscape/api/__init__.py +26 -0
  3. entryscape/api/app_token_api.py +835 -0
  4. entryscape/api/auth_api.py +965 -0
  5. entryscape/api/catalog_api.py +4473 -0
  6. entryscape/api/contact_api.py +3135 -0
  7. entryscape/api/dataservice_api.py +3135 -0
  8. entryscape/api/dataset_api.py +3804 -0
  9. entryscape/api/distribution_api.py +3135 -0
  10. entryscape/api/document_api.py +2740 -0
  11. entryscape/api/idea_api.py +2740 -0
  12. entryscape/api/job_api.py +360 -0
  13. entryscape/api/model_api.py +2446 -0
  14. entryscape/api/model_class_api.py +2611 -0
  15. entryscape/api/model_diagram_api.py +2611 -0
  16. entryscape/api/model_field_api.py +2611 -0
  17. entryscape/api/model_form_api.py +2611 -0
  18. entryscape/api/model_namespace_api.py +2611 -0
  19. entryscape/api/model_property_api.py +2611 -0
  20. entryscape/api/organization_api.py +3135 -0
  21. entryscape/api/search_api.py +1513 -0
  22. entryscape/api/showcase_api.py +2740 -0
  23. entryscape/api/suggestion_api.py +2740 -0
  24. entryscape/api/terminology_api.py +1726 -0
  25. entryscape/api/upload_api.py +814 -0
  26. entryscape/api_client.py +763 -0
  27. entryscape/api_response.py +20 -0
  28. entryscape/configuration.py +673 -0
  29. entryscape/exceptions.py +222 -0
  30. entryscape/models/__init__.py +71 -0
  31. entryscape/models/app_token.py +156 -0
  32. entryscape/models/app_token_create_request.py +98 -0
  33. entryscape/models/app_token_create_response.py +169 -0
  34. entryscape/models/app_token_status.py +35 -0
  35. entryscape/models/app_token_verify_request.py +109 -0
  36. entryscape/models/entity_list_item.py +175 -0
  37. entryscape/models/entity_list_response.py +139 -0
  38. entryscape/models/entity_reference.py +189 -0
  39. entryscape/models/entity_type.py +57 -0
  40. entryscape/models/error.py +135 -0
  41. entryscape/models/facet_field.py +115 -0
  42. entryscape/models/facet_field_values_inner.py +100 -0
  43. entryscape/models/facet_list.py +113 -0
  44. entryscape/models/facet_list_available_inner.py +107 -0
  45. entryscape/models/job_response.py +112 -0
  46. entryscape/models/job_status.py +189 -0
  47. entryscape/models/job_status_progress.py +100 -0
  48. entryscape/models/job_status_value.py +37 -0
  49. entryscape/models/job_type.py +37 -0
  50. entryscape/models/list_catalogs_entry_type_parameter.py +37 -0
  51. entryscape/models/list_catalogs_graph_type_parameter.py +44 -0
  52. entryscape/models/list_catalogs_resource_type_parameter.py +37 -0
  53. entryscape/models/login_request.py +108 -0
  54. entryscape/models/login_response.py +115 -0
  55. entryscape/models/metadata_format.py +38 -0
  56. entryscape/models/metadata_request.py +99 -0
  57. entryscape/models/parent_reference.py +130 -0
  58. entryscape/models/search_request.py +158 -0
  59. entryscape/models/search_request_filters.py +144 -0
  60. entryscape/models/search_request_filters_graph_type.py +44 -0
  61. entryscape/models/search_request_filters_resource_type.py +37 -0
  62. entryscape/models/search_request_sort.py +38 -0
  63. entryscape/models/search_request_sort_order.py +35 -0
  64. entryscape/models/search_response.py +175 -0
  65. entryscape/models/search_result.py +175 -0
  66. entryscape/models/search_result_graph_type.py +44 -0
  67. entryscape/models/search_result_resource_type.py +37 -0
  68. entryscape/models/search_sort_order_parameter.py +35 -0
  69. entryscape/models/terminology_import_mode.py +35 -0
  70. entryscape/models/validation_profile.py +36 -0
  71. entryscape/models/validation_response.py +149 -0
  72. entryscape/models/validation_result.py +162 -0
  73. entryscape/models/validation_severity.py +36 -0
  74. entryscape/models/validation_summary.py +122 -0
  75. entryscape/models/whoami_response.py +104 -0
  76. entryscape/py.typed +0 -0
  77. entryscape/rest.py +210 -0
  78. entryscape-1.3.0.dist-info/METADATA +696 -0
  79. entryscape-1.3.0.dist-info/RECORD +82 -0
  80. entryscape-1.3.0.dist-info/WHEEL +5 -0
  81. entryscape-1.3.0.dist-info/licenses/LICENSE.txt +165 -0
  82. entryscape-1.3.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,763 @@
1
+ """
2
+ EntryScape API
3
+
4
+ This API provides structured access to EntryScape data following DCAT-AP standards. All entity endpoints follow a consistent pattern: - GET /{entity} - List all entities - POST /{entity} - Create a new entity (DCAT types only) - GET /{entity}/{context_id}/{entry_id} - Get entity reference info - DELETE /{entity}/{context_id}/{entry_id} - Delete an entity (DCAT types only) - GET /{entity}/{context_id}/{entry_id}/metadata - Get raw RDF metadata - PUT /{entity}/{context_id}/{entry_id}/metadata - Replace raw RDF metadata (JSON-LD, Turtle, RDF/XML, or N-Triples passthrough) ## Reading and consistency Reads of a single entity — `GET /{entity}/{context_id}/{entry_id}` and its `/metadata` — go straight to the store and always reflect the latest write. Lists and search do not. They are answered from a search index that is updated asynchronously, so for a short interval after a write: - an entry that was just created may be missing from the list it belongs to, while reading it by id already works; - an entry that was just deleted may still appear; - `results` counts what the index holds, not what the store holds. Write a client that tolerates this: after creating an entry, use the id the create returned rather than searching for what you just wrote. `results` is also an upper bound rather than an exact count when the caller cannot read every hit (see the field's own description). Separately, responses are cached for 15 minutes by default, which is a second and unrelated source of staleness. A write invalidates the cache entries it affects, but a read that lands in the indexing gap can cache a list that does not yet show it. ## Authentication Most endpoints require an authenticated session. Reading public data works without authentication, while creating, updating, and deleting entities requires a valid user session. 1. **Log in** with `POST /auth/login`, supplying an EntryStore username and password. The response returns an `auth_token`. 2. **Send the token** on subsequent requests via the `X-Auth-Token` header. This is the recommended method for SDK and programmatic access. Browser clients can instead rely on the `auth_token` cookie, which the server sets automatically on login (`SameSite=Lax; Secure`). 3. **Inspect the session** with `GET /auth/whoami`, which returns the current user or an anonymous/guest identity when no valid token is supplied. 4. **Log out** with `POST /auth/logout` to invalidate the token and clear the cookie. ### Writes and CSRF Send the token as the `X-Auth-Token` **header** and there is nothing else to do: creates, updates and deletes work as they are, which is how the SDKs and the MCP server are built. The `auth_token` cookie is different. A cookie is attached by the browser automatically, so a state-changing request authenticated by it alone is what cross-site request forgery abuses, and those requests additionally need a double-submit token: read the `XSRF-TOKEN` cookie the server sets on any response and send its value back as the `X-XSRF-TOKEN` header. Without it the request is rejected with `403` before it reaches the endpoint. A custom header cannot be forged this way — cross-origin JavaScript cannot set one without a CORS preflight, which this API grants only to configured origins — so the header is the recommended path for anything that is not a browser session. ### App Tokens An app token identifies an integration. Create one with `POST /app-token` (unauthenticated). Creation requires an email address: the token starts in the `pending` state and a 6-digit code is emailed to the owner. Confirm the code with `POST /app-token/verify` to activate the token and receive its value, which is shown only once — store it securely. `GET /app-token/{app_token_id}` then returns its details and quota usage, authenticated by the token itself via the `X-App-Token` header. **The `X-App-Token` header is accepted only by `GET /app-token/{app_token_id}`.** No other operation reads it, and the read quota is recorded but not yet enforced: reading public data needs no token of any kind, and sending an app token with a read neither grants nor meters anything. Metered public read access is the intent of the two-token model, not a description of this release — see the `security` declared on each operation for what it actually accepts. ## SDKs Generated clients for Python, TypeScript, JavaScript and C# wrap every operation below, and each operation on this page shows the SDK call beside the `curl` command. Two of them install from a public registry: ``` pip install entryscape # Python npm install @entryscape/api-client # TypeScript and JavaScript ``` `@entryscape/api-client` ships an ESM and a CommonJS build, so `import` and `require()` both work and TypeScript is not required to use it — the name describes what it is written in, not what you have to write. There is a separate generated JavaScript SDK, and it is deliberately **not** on npm; this package is the npm client for both languages. Every SDK, including the C# and JavaScript ones, is also published as a tarball. The downloads are linked in the sidebar, they are the route to take when a registry is unreachable or a build has to vendor its dependencies, and each archive carries the SDK's own README: - **Python** — `pip install entryscape`, or `python-sdk.tar.gz`. - **TypeScript and JavaScript** — `npm install @entryscape/api-client`, or `typescript-sdk.tar.gz`. - **JavaScript (the separate generated client)** — not published to a registry, by design; `javascript-sdk.tar.gz` only. - **C#** — not published to NuGet yet; `csharp-sdk.tar.gz` only. - **MCP server** — `npx -y @entryscape/mcp-server`, or `mcp-server.tar.gz`. ## MCP Server A Model Context Protocol (MCP) server is generated from this specification and published alongside the SDKs (`@entryscape/mcp-server`), exposing the API as tools for AI assistants and agents. Each operation becomes one tool named after its `operationId` — `listDatasets`, `createCatalog`, `search`, `getJobStatus`. The `auth` operations are the exception: the server reads its token once at startup, so a `login` tool could install nothing and a `logout` tool would only invalidate the token the server was started with. On connect the server also hands the assistant a short set of rules that hold across every tool: a token is bound to one EntryStore instance, the search index lags a write, uploads finish as jobs. ### Install The server is on npm, and MCP servers are normally launched straight from there, so nothing has to be installed first: ``` npx -y @entryscape/mcp-server ``` `npm install -g @entryscape/mcp-server` works too and puts an `entryscape-mcp` binary on `PATH`. It is also listed in the MCP Registry as `com.entryscape/mcp-server`, which is where clients and marketplaces look it up. Without npm, download `mcp-server.tar.gz` from the SDK downloads and unpack it. The package ships prebuilt; install its runtime dependency once: ``` mkdir entryscape-mcp && tar -xzf mcp-server.tar.gz -C entryscape-mcp cd entryscape-mcp && npm install --omit=dev ``` ### Configure The server is a stdio MCP server configured through environment variables, read once at startup: - `ENTRYSCAPE_API_URL` — base URL of the API server, path included. Required: there is no default, and the server refuses to start without it. - `ENTRYSCAPE_AUTH_TOKEN` — a session token from `POST /auth/login`, sent as the `X-Auth-Token` header. Optional: without it reads see public entries and every write is refused. A token is valid only for the EntryStore instance that issued it. - `ENTRYSCAPE_ENTRYSTORE_HOST` — the EntryStore instance the API server should use, for example `dev.entryscape.com/store/`. Unset means the API server's own default. - `ENTRYSCAPE_MCP_UPLOAD_ROOT` — the directory the upload tools may read files from. **Unset means uploads are disabled**: `addFileToDistribution`, `replaceFileInDistribution` and `importTerminology` refuse and say so. - `ENTRYSCAPE_MCP_TAGS` — comma-separated tags to serve tools for, for example `catalog,dataset,distribution,search`. Unset serves every tool. The package's `README.md` lists the remaining variables (timeouts and size caps). Register the server with any MCP-capable client by adding it to the client's `mcpServers` configuration: ```json { \"mcpServers\": { \"entryscape\": { \"command\": \"npx\", \"args\": [\"-y\", \"@entryscape/mcp-server\"], \"env\": { \"ENTRYSCAPE_API_URL\": \"https://<your EntryScape API host>\", \"ENTRYSCAPE_AUTH_TOKEN\": \"your-session-token\" } } } } ``` From an unpacked download instead, the command is `\"command\": \"node\", \"args\": [\"/path/to/entryscape-mcp/dist/bin/entryscape-mcp.js\"]`. ### Claude Code The unpacked package is also a Claude Code plugin, so one install gives the server and the skills below together. Claude Code installs plugins from marketplaces, and the package carries a one-entry marketplace pointing at itself: ``` claude plugin marketplace add /path/to/entryscape-mcp claude plugin install entryscape@entryscape --scope user ``` The plugin passes `ENTRYSCAPE_API_URL`, `ENTRYSCAPE_AUTH_TOKEN`, `ENTRYSCAPE_ENTRYSTORE_HOST`, `ENTRYSCAPE_MCP_TAGS` and `ENTRYSCAPE_MCP_UPLOAD_ROOT` through from the shell Claude Code was started in, so set them there. To try the plugin for one session without installing it, start Claude Code with `--plugin-dir /path/to/entryscape-mcp`. ### Skills `skills/` in the package holds procedures that span several tools, in the Agent Skills format (a `SKILL.md` with `name` and `description`): which tools to call in which order, what to check between calls, and where to stop. Claude Code loads them from the plugin; other clients that read the format can be pointed at the directory. The `find` skill covers discovery, facets and selective metadata reads; `publish-dataset` takes a dataset from catalog to validated distribution with its file; `edit-metadata` changes an entry that already exists without dropping the rest of its graph, models included; `migrate-from-taskrunner` moves an integration off the deprecated Taskrunner API. Every tool a skill names is checked against this specification when the package is built. ## Deprecation Policy When endpoints or features are deprecated: 1. The operation is marked with `deprecated: true` in this spec 2. The operation description documents the replacement endpoint and sunset date 3. Deprecated endpoints remain functional for at least 6 months after announcement 4. The server returns a `Sunset` header with the planned removal date 5. After the sunset date, the endpoint may be removed in a future release
5
+
6
+ The version of the OpenAPI document: 1.3.0
7
+ Contact: contact@entryscape.com
8
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
9
+
10
+ Do not edit the class manually.
11
+ """ # noqa: E501
12
+
13
+ import datetime
14
+ from dateutil.parser import parse
15
+ from enum import Enum
16
+ import decimal
17
+ import json
18
+ import mimetypes
19
+ import os
20
+ import re
21
+ import tempfile
22
+ import uuid
23
+
24
+ from urllib.parse import quote
25
+ from typing import Tuple, Optional, List, Dict, Union
26
+ from pydantic import SecretStr
27
+
28
+ from entryscape.configuration import Configuration
29
+ from entryscape.api_response import ApiResponse, T as ApiResponseT
30
+ import entryscape.models
31
+ from entryscape import rest
32
+ from entryscape.exceptions import (
33
+ ApiValueError,
34
+ ApiException,
35
+ BadRequestException,
36
+ UnauthorizedException,
37
+ ForbiddenException,
38
+ NotFoundException,
39
+ ServiceException,
40
+ )
41
+
42
+ RequestSerialized = Tuple[str, str, Dict[str, str], Optional[str], List[str]]
43
+
44
+
45
+ class ApiClient:
46
+ """Generic API client for OpenAPI client library builds.
47
+
48
+ OpenAPI generic API client. This client handles the client-
49
+ server communication, and is invariant across implementations. Specifics of
50
+ the methods and models for each application are generated from the OpenAPI
51
+ templates.
52
+
53
+ :param configuration: .Configuration object for this client
54
+ :param header_name: a header to pass when making calls to the API.
55
+ :param header_value: a header value to pass when making calls to
56
+ the API.
57
+ :param cookie: a cookie to include in the header when making calls
58
+ to the API
59
+ """
60
+
61
+ PRIMITIVE_TYPES = (float, bool, bytes, str, int)
62
+ NATIVE_TYPES_MAPPING = {
63
+ "int": int,
64
+ "long": int, # TODO remove as only py3 is supported?
65
+ "float": float,
66
+ "str": str,
67
+ "bool": bool,
68
+ "date": datetime.date,
69
+ "datetime": datetime.datetime,
70
+ "decimal": decimal.Decimal,
71
+ "UUID": uuid.UUID,
72
+ "object": object,
73
+ }
74
+ _pool = None
75
+
76
+ def __init__(
77
+ self, configuration=None, header_name=None, header_value=None, cookie=None
78
+ ) -> None:
79
+ # use default configuration if none is provided
80
+ if configuration is None:
81
+ configuration = Configuration.get_default()
82
+ self.configuration = configuration
83
+
84
+ self.rest_client = rest.RESTClientObject(configuration)
85
+ self.default_headers = {}
86
+ if header_name is not None:
87
+ self.default_headers[header_name] = header_value
88
+ self.cookie = cookie
89
+ # Set default User-Agent.
90
+ self.user_agent = "OpenAPI-Generator/1.3.0/python"
91
+ self.client_side_validation = configuration.client_side_validation
92
+
93
+ async def __aenter__(self):
94
+ return self
95
+
96
+ async def __aexit__(self, exc_type, exc_value, traceback):
97
+ await self.close()
98
+
99
+ async def close(self):
100
+ await self.rest_client.close()
101
+
102
+ @property
103
+ def user_agent(self):
104
+ """User agent for this API client"""
105
+ return self.default_headers["User-Agent"]
106
+
107
+ @user_agent.setter
108
+ def user_agent(self, value):
109
+ self.default_headers["User-Agent"] = value
110
+
111
+ def set_default_header(self, header_name, header_value):
112
+ self.default_headers[header_name] = header_value
113
+
114
+ _default = None
115
+
116
+ @classmethod
117
+ def get_default(cls):
118
+ """Return new instance of ApiClient.
119
+
120
+ This method returns newly created, based on default constructor,
121
+ object of ApiClient class or returns a copy of default
122
+ ApiClient.
123
+
124
+ :return: The ApiClient object.
125
+ """
126
+ if cls._default is None:
127
+ cls._default = ApiClient()
128
+ return cls._default
129
+
130
+ @classmethod
131
+ def set_default(cls, default):
132
+ """Set default instance of ApiClient.
133
+
134
+ It stores default ApiClient.
135
+
136
+ :param default: object of ApiClient.
137
+ """
138
+ cls._default = default
139
+
140
+ def param_serialize(
141
+ self,
142
+ method,
143
+ resource_path,
144
+ path_params=None,
145
+ query_params=None,
146
+ header_params=None,
147
+ body=None,
148
+ post_params=None,
149
+ files=None,
150
+ auth_settings=None,
151
+ collection_formats=None,
152
+ _host=None,
153
+ _request_auth=None,
154
+ ) -> RequestSerialized:
155
+ """Builds the HTTP request params needed by the request.
156
+ :param method: Method to call.
157
+ :param resource_path: Path to method endpoint.
158
+ :param path_params: Path parameters in the url.
159
+ :param query_params: Query parameters in the url.
160
+ :param header_params: Header parameters to be
161
+ placed in the request header.
162
+ :param body: Request body.
163
+ :param post_params dict: Request post form parameters,
164
+ for `application/x-www-form-urlencoded`, `multipart/form-data`.
165
+ :param auth_settings list: Auth Settings names for the request.
166
+ :param files dict: key -> filename, value -> filepath,
167
+ for `multipart/form-data`.
168
+ :param collection_formats: dict of collection formats for path, query,
169
+ header, and post parameters.
170
+ :param _request_auth: set to override the auth_settings for an a single
171
+ request; this effectively ignores the authentication
172
+ in the spec for a single request.
173
+ :return: tuple of form (path, http_method, query_params, header_params,
174
+ body, post_params, files)
175
+ """
176
+
177
+ config = self.configuration
178
+
179
+ # header parameters
180
+ header_params = header_params or {}
181
+ header_params.update(self.default_headers)
182
+ if self.cookie:
183
+ header_params["Cookie"] = self.cookie
184
+ if header_params:
185
+ header_params = self.sanitize_for_serialization(header_params)
186
+ header_params = dict(
187
+ self.parameters_to_tuples(header_params, collection_formats)
188
+ )
189
+
190
+ # path parameters
191
+ if path_params:
192
+ path_params = self.sanitize_for_serialization(path_params)
193
+ path_params = self.parameters_to_tuples(path_params, collection_formats)
194
+ for k, v in path_params:
195
+ # specified safe chars, encode everything
196
+ resource_path = resource_path.replace(
197
+ "{%s}" % k, quote(str(v), safe=config.safe_chars_for_path_param)
198
+ )
199
+
200
+ # post parameters
201
+ if post_params or files:
202
+ post_params = post_params if post_params else []
203
+ post_params = self.sanitize_for_serialization(post_params)
204
+ post_params = self.parameters_to_tuples(post_params, collection_formats)
205
+ if files:
206
+ post_params.extend(self.files_parameters(files))
207
+
208
+ # auth setting
209
+ self.update_params_for_auth(
210
+ header_params,
211
+ query_params,
212
+ auth_settings,
213
+ resource_path,
214
+ method,
215
+ body,
216
+ request_auth=_request_auth,
217
+ )
218
+
219
+ # body
220
+ if body:
221
+ body = self.sanitize_for_serialization(body)
222
+
223
+ # request url
224
+ if _host is None or self.configuration.ignore_operation_servers:
225
+ url = self.configuration.host + resource_path
226
+ else:
227
+ # use server/host defined in path or operation instead
228
+ url = _host + resource_path
229
+
230
+ # query parameters
231
+ if query_params:
232
+ query_params = self.sanitize_for_serialization(query_params)
233
+ url_query = self.parameters_to_url_query(query_params, collection_formats)
234
+ url += "?" + url_query
235
+
236
+ return method, url, header_params, body, post_params
237
+
238
+ async def call_api(
239
+ self,
240
+ method,
241
+ url,
242
+ header_params=None,
243
+ body=None,
244
+ post_params=None,
245
+ _request_timeout=None,
246
+ ) -> rest.RESTResponse:
247
+ """Makes the HTTP request (synchronous)
248
+ :param method: Method to call.
249
+ :param url: Path to method endpoint.
250
+ :param header_params: Header parameters to be
251
+ placed in the request header.
252
+ :param body: Request body.
253
+ :param post_params dict: Request post form parameters,
254
+ for `application/x-www-form-urlencoded`, `multipart/form-data`.
255
+ :param _request_timeout: timeout setting for this request.
256
+ :return: RESTResponse
257
+ """
258
+
259
+ try:
260
+ # perform request and return response
261
+ response_data = await self.rest_client.request(
262
+ method,
263
+ url,
264
+ headers=header_params,
265
+ body=body,
266
+ post_params=post_params,
267
+ _request_timeout=_request_timeout,
268
+ )
269
+
270
+ except ApiException as e:
271
+ raise e
272
+
273
+ return response_data
274
+
275
+ def response_deserialize(
276
+ self,
277
+ response_data: rest.RESTResponse,
278
+ response_types_map: Optional[Dict[str, ApiResponseT]] = None,
279
+ ) -> ApiResponse[ApiResponseT]:
280
+ """Deserializes response into an object.
281
+ :param response_data: RESTResponse object to be deserialized.
282
+ :param response_types_map: dict of response types.
283
+ :return: ApiResponse
284
+ """
285
+
286
+ msg = "RESTResponse.read() must be called before passing it to response_deserialize()"
287
+ assert response_data.data is not None, msg
288
+
289
+ response_type = response_types_map.get(str(response_data.status), None)
290
+ if (
291
+ not response_type
292
+ and isinstance(response_data.status, int)
293
+ and 100 <= response_data.status <= 599
294
+ ):
295
+ # if not found, look for '1XX', '2XX', etc.
296
+ response_type = response_types_map.get(
297
+ str(response_data.status)[0] + "XX", None
298
+ )
299
+
300
+ # deserialize response data
301
+ response_text = None
302
+ return_data = None
303
+ try:
304
+ if response_type in ("bytearray", "bytes"):
305
+ return_data = response_data.data
306
+ elif response_type == "file":
307
+ return_data = self.__deserialize_file(response_data)
308
+ elif response_type is not None:
309
+ match = None
310
+ content_type = response_data.headers.get("content-type")
311
+ if content_type is not None:
312
+ match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type)
313
+ encoding = match.group(1) if match else "utf-8"
314
+ response_text = response_data.data.decode(encoding)
315
+ return_data = self.deserialize(
316
+ response_text, response_type, content_type
317
+ )
318
+ finally:
319
+ if not 200 <= response_data.status <= 299:
320
+ raise ApiException.from_response(
321
+ http_resp=response_data,
322
+ body=response_text,
323
+ data=return_data,
324
+ )
325
+
326
+ return ApiResponse(
327
+ status_code=response_data.status,
328
+ data=return_data,
329
+ headers=response_data.headers,
330
+ raw_data=response_data.data,
331
+ )
332
+
333
+ def sanitize_for_serialization(self, obj):
334
+ """Builds a JSON POST object.
335
+
336
+ If obj is None, return None.
337
+ If obj is SecretStr, return obj.get_secret_value()
338
+ If obj is str, int, long, float, bool, return directly.
339
+ If obj is datetime.datetime, datetime.date
340
+ convert to string in iso8601 format.
341
+ If obj is decimal.Decimal return string representation.
342
+ If obj is list, sanitize each element in the list.
343
+ If obj is dict, return the dict.
344
+ If obj is OpenAPI model, return the properties dict.
345
+
346
+ :param obj: The data to serialize.
347
+ :return: The serialized form of data.
348
+ """
349
+ if obj is None:
350
+ return None
351
+ elif isinstance(obj, Enum):
352
+ return obj.value
353
+ elif isinstance(obj, SecretStr):
354
+ return obj.get_secret_value()
355
+ elif isinstance(obj, self.PRIMITIVE_TYPES):
356
+ return obj
357
+ elif isinstance(obj, uuid.UUID):
358
+ return str(obj)
359
+ elif isinstance(obj, list):
360
+ return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj]
361
+ elif isinstance(obj, tuple):
362
+ return tuple(self.sanitize_for_serialization(sub_obj) for sub_obj in obj)
363
+ elif isinstance(obj, (datetime.datetime, datetime.date)):
364
+ return obj.isoformat()
365
+ elif isinstance(obj, decimal.Decimal):
366
+ return str(obj)
367
+ elif isinstance(obj, dict):
368
+ return {
369
+ key: self.sanitize_for_serialization(val) for key, val in obj.items()
370
+ }
371
+
372
+ # Convert model obj to dict except
373
+ # attributes `openapi_types`, `attribute_map`
374
+ # and attributes which value is not None.
375
+ # Convert attribute name to json key in
376
+ # model definition for request.
377
+ if hasattr(obj, "to_dict") and callable(getattr(obj, "to_dict")):
378
+ obj_dict = obj.to_dict()
379
+ else:
380
+ obj_dict = obj.__dict__
381
+
382
+ return self.sanitize_for_serialization(obj_dict)
383
+
384
+ def deserialize(
385
+ self, response_text: str, response_type: str, content_type: Optional[str]
386
+ ):
387
+ """Deserializes response into an object.
388
+
389
+ :param response: RESTResponse object to be deserialized.
390
+ :param response_type: class literal for
391
+ deserialized object, or string of class name.
392
+ :param content_type: content type of response.
393
+
394
+ :return: deserialized object.
395
+ """
396
+
397
+ # fetch data from response object
398
+ if content_type is None:
399
+ try:
400
+ data = json.loads(response_text)
401
+ except ValueError:
402
+ data = response_text
403
+ elif re.match(
404
+ r"^application/(json|[\w!#$&.+\-^_]+\+json)\s*(;|$)",
405
+ content_type,
406
+ re.IGNORECASE,
407
+ ):
408
+ if response_text == "":
409
+ data = ""
410
+ else:
411
+ data = json.loads(response_text)
412
+ elif re.match(r"^text\/[a-z.+-]+\s*(;|$)", content_type, re.IGNORECASE):
413
+ data = response_text
414
+ else:
415
+ raise ApiException(
416
+ status=0, reason="Unsupported content type: {0}".format(content_type)
417
+ )
418
+
419
+ return self.__deserialize(data, response_type)
420
+
421
+ def __deserialize(self, data, klass):
422
+ """Deserializes dict, list, str into an object.
423
+
424
+ :param data: dict, list or str.
425
+ :param klass: class literal, or string of class name.
426
+
427
+ :return: object.
428
+ """
429
+ if data is None:
430
+ return None
431
+
432
+ if isinstance(klass, str):
433
+ if klass.startswith("List["):
434
+ m = re.match(r"List\[(.*)]", klass)
435
+ assert m is not None, "Malformed List type definition"
436
+ sub_kls = m.group(1)
437
+ return [self.__deserialize(sub_data, sub_kls) for sub_data in data]
438
+
439
+ if klass.startswith("Dict["):
440
+ m = re.match(r"Dict\[([^,]*), (.*)]", klass)
441
+ assert m is not None, "Malformed Dict type definition"
442
+ sub_kls = m.group(2)
443
+ return {k: self.__deserialize(v, sub_kls) for k, v in data.items()}
444
+
445
+ # convert str to class
446
+ if klass in self.NATIVE_TYPES_MAPPING:
447
+ klass = self.NATIVE_TYPES_MAPPING[klass]
448
+ else:
449
+ klass = getattr(entryscape.models, klass)
450
+
451
+ if klass in self.PRIMITIVE_TYPES:
452
+ return self.__deserialize_primitive(data, klass)
453
+ elif klass is object:
454
+ return self.__deserialize_object(data)
455
+ elif klass is datetime.date:
456
+ return self.__deserialize_date(data)
457
+ elif klass is datetime.datetime:
458
+ return self.__deserialize_datetime(data)
459
+ elif klass is decimal.Decimal:
460
+ return decimal.Decimal(data)
461
+ elif klass is uuid.UUID:
462
+ return uuid.UUID(data)
463
+ elif issubclass(klass, Enum):
464
+ return self.__deserialize_enum(data, klass)
465
+ else:
466
+ return self.__deserialize_model(data, klass)
467
+
468
+ def parameters_to_tuples(self, params, collection_formats):
469
+ """Get parameters as list of tuples, formatting collections.
470
+
471
+ :param params: Parameters as dict or list of two-tuples
472
+ :param dict collection_formats: Parameter collection formats
473
+ :return: Parameters as list of tuples, collections formatted
474
+ """
475
+ new_params: List[Tuple[str, str]] = []
476
+ if collection_formats is None:
477
+ collection_formats = {}
478
+ for k, v in params.items() if isinstance(params, dict) else params:
479
+ if k in collection_formats:
480
+ collection_format = collection_formats[k]
481
+ if collection_format == "multi":
482
+ new_params.extend((k, value) for value in v)
483
+ else:
484
+ if collection_format == "ssv":
485
+ delimiter = " "
486
+ elif collection_format == "tsv":
487
+ delimiter = "\t"
488
+ elif collection_format == "pipes":
489
+ delimiter = "|"
490
+ else: # csv is the default
491
+ delimiter = ","
492
+ new_params.append((k, delimiter.join(str(value) for value in v)))
493
+ else:
494
+ new_params.append((k, v))
495
+ return new_params
496
+
497
+ def parameters_to_url_query(self, params, collection_formats):
498
+ """Get parameters as list of tuples, formatting collections.
499
+
500
+ :param params: Parameters as dict or list of two-tuples
501
+ :param dict collection_formats: Parameter collection formats
502
+ :return: URL query string (e.g. a=Hello%20World&b=123)
503
+ """
504
+ new_params: List[Tuple[str, str]] = []
505
+ if collection_formats is None:
506
+ collection_formats = {}
507
+ for k, v in params.items() if isinstance(params, dict) else params:
508
+ if isinstance(v, bool):
509
+ v = str(v).lower()
510
+ if isinstance(v, (int, float)):
511
+ v = str(v)
512
+ if isinstance(v, dict):
513
+ v = json.dumps(v)
514
+
515
+ if k in collection_formats:
516
+ collection_format = collection_formats[k]
517
+ if collection_format == "multi":
518
+ new_params.extend((k, quote(str(value))) for value in v)
519
+ else:
520
+ if collection_format == "ssv":
521
+ delimiter = " "
522
+ elif collection_format == "tsv":
523
+ delimiter = "\t"
524
+ elif collection_format == "pipes":
525
+ delimiter = "|"
526
+ else: # csv is the default
527
+ delimiter = ","
528
+ new_params.append(
529
+ (k, delimiter.join(quote(str(value)) for value in v))
530
+ )
531
+ else:
532
+ new_params.append((k, quote(str(v))))
533
+
534
+ return "&".join(["=".join(map(str, item)) for item in new_params])
535
+
536
+ def files_parameters(
537
+ self,
538
+ files: Dict[str, Union[str, bytes, List[str], List[bytes], Tuple[str, bytes]]],
539
+ ):
540
+ """Builds form parameters.
541
+
542
+ :param files: File parameters.
543
+ :return: Form parameters with files.
544
+ """
545
+ params = []
546
+ for k, v in files.items():
547
+ if isinstance(v, str):
548
+ with open(v, "rb") as f:
549
+ filename = os.path.basename(f.name)
550
+ filedata = f.read()
551
+ elif isinstance(v, bytes):
552
+ filename = k
553
+ filedata = v
554
+ elif isinstance(v, tuple):
555
+ filename, filedata = v
556
+ elif isinstance(v, list):
557
+ for file_param in v:
558
+ params.extend(self.files_parameters({k: file_param}))
559
+ continue
560
+ else:
561
+ raise ValueError("Unsupported file value")
562
+ mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream"
563
+ params.append(tuple([k, tuple([filename, filedata, mimetype])]))
564
+ return params
565
+
566
+ def select_header_accept(self, accepts: List[str]) -> Optional[str]:
567
+ """Returns `Accept` based on an array of accepts provided.
568
+
569
+ :param accepts: List of headers.
570
+ :return: Accept (e.g. application/json).
571
+ """
572
+ if not accepts:
573
+ return None
574
+
575
+ for accept in accepts:
576
+ if re.search("json", accept, re.IGNORECASE):
577
+ return accept
578
+
579
+ return accepts[0]
580
+
581
+ def select_header_content_type(self, content_types):
582
+ """Returns `Content-Type` based on an array of content_types provided.
583
+
584
+ :param content_types: List of content-types.
585
+ :return: Content-Type (e.g. application/json).
586
+ """
587
+ if not content_types:
588
+ return None
589
+
590
+ for content_type in content_types:
591
+ if re.search("json", content_type, re.IGNORECASE):
592
+ return content_type
593
+
594
+ return content_types[0]
595
+
596
+ def update_params_for_auth(
597
+ self,
598
+ headers,
599
+ queries,
600
+ auth_settings,
601
+ resource_path,
602
+ method,
603
+ body,
604
+ request_auth=None,
605
+ ) -> None:
606
+ """Updates header and query params based on authentication setting.
607
+
608
+ :param headers: Header parameters dict to be updated.
609
+ :param queries: Query parameters tuple list to be updated.
610
+ :param auth_settings: Authentication setting identifiers list.
611
+ :resource_path: A string representation of the HTTP request resource path.
612
+ :method: A string representation of the HTTP request method.
613
+ :body: A object representing the body of the HTTP request.
614
+ The object type is the return value of sanitize_for_serialization().
615
+ :param request_auth: if set, the provided settings will
616
+ override the token in the configuration.
617
+ """
618
+ if not auth_settings:
619
+ return
620
+
621
+ if request_auth:
622
+ self._apply_auth_params(
623
+ headers, queries, resource_path, method, body, request_auth
624
+ )
625
+ else:
626
+ for auth in auth_settings:
627
+ auth_setting = self.configuration.auth_settings().get(auth)
628
+ if auth_setting:
629
+ self._apply_auth_params(
630
+ headers, queries, resource_path, method, body, auth_setting
631
+ )
632
+
633
+ def _apply_auth_params(
634
+ self, headers, queries, resource_path, method, body, auth_setting
635
+ ) -> None:
636
+ """Updates the request parameters based on a single auth_setting
637
+
638
+ :param headers: Header parameters dict to be updated.
639
+ :param queries: Query parameters tuple list to be updated.
640
+ :resource_path: A string representation of the HTTP request resource path.
641
+ :method: A string representation of the HTTP request method.
642
+ :body: A object representing the body of the HTTP request.
643
+ The object type is the return value of sanitize_for_serialization().
644
+ :param auth_setting: auth settings for the endpoint
645
+ """
646
+ if auth_setting["in"] == "cookie":
647
+ headers["Cookie"] = auth_setting["value"]
648
+ elif auth_setting["in"] == "header":
649
+ if auth_setting["type"] != "http-signature":
650
+ headers[auth_setting["key"]] = auth_setting["value"]
651
+ elif auth_setting["in"] == "query":
652
+ queries.append((auth_setting["key"], auth_setting["value"]))
653
+ else:
654
+ raise ApiValueError("Authentication token must be in `query` or `header`")
655
+
656
+ def __deserialize_file(self, response):
657
+ """Deserializes body to file
658
+
659
+ Saves response body into a file in a temporary folder,
660
+ using the filename from the `Content-Disposition` header if provided.
661
+
662
+ handle file downloading
663
+ save response body into a tmp file and return the instance
664
+
665
+ :param response: RESTResponse.
666
+ :return: file path.
667
+ """
668
+ fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path)
669
+ os.close(fd)
670
+ os.remove(path)
671
+
672
+ content_disposition = response.headers.get("Content-Disposition")
673
+ if content_disposition:
674
+ m = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition)
675
+ assert m is not None, "Unexpected 'content-disposition' header value"
676
+ filename = os.path.basename(m.group(1)) # Strip any directory traversal
677
+ if filename in ("", ".", ".."): # fall back to tmp filename
678
+ filename = os.path.basename(path)
679
+ path = os.path.join(os.path.dirname(path), filename)
680
+
681
+ with open(path, "wb") as f:
682
+ f.write(response.data)
683
+
684
+ return path
685
+
686
+ def __deserialize_primitive(self, data, klass):
687
+ """Deserializes string to primitive type.
688
+
689
+ :param data: str.
690
+ :param klass: class literal.
691
+
692
+ :return: int, long, float, str, bool.
693
+ """
694
+ try:
695
+ return klass(data)
696
+ except UnicodeEncodeError:
697
+ return str(data)
698
+ except TypeError:
699
+ return data
700
+
701
+ def __deserialize_object(self, value):
702
+ """Return an original value.
703
+
704
+ :return: object.
705
+ """
706
+ return value
707
+
708
+ def __deserialize_date(self, string):
709
+ """Deserializes string to date.
710
+
711
+ :param string: str.
712
+ :return: date.
713
+ """
714
+ try:
715
+ return parse(string).date()
716
+ except ImportError:
717
+ return string
718
+ except ValueError:
719
+ raise rest.ApiException(
720
+ status=0, reason="Failed to parse `{0}` as date object".format(string)
721
+ )
722
+
723
+ def __deserialize_datetime(self, string):
724
+ """Deserializes string to datetime.
725
+
726
+ The string should be in iso8601 datetime format.
727
+
728
+ :param string: str.
729
+ :return: datetime.
730
+ """
731
+ try:
732
+ return parse(string)
733
+ except ImportError:
734
+ return string
735
+ except ValueError:
736
+ raise rest.ApiException(
737
+ status=0,
738
+ reason=("Failed to parse `{0}` as datetime object".format(string)),
739
+ )
740
+
741
+ def __deserialize_enum(self, data, klass):
742
+ """Deserializes primitive type to enum.
743
+
744
+ :param data: primitive type.
745
+ :param klass: class literal.
746
+ :return: enum value.
747
+ """
748
+ try:
749
+ return klass(data)
750
+ except ValueError:
751
+ raise rest.ApiException(
752
+ status=0, reason=("Failed to parse `{0}` as `{1}`".format(data, klass))
753
+ )
754
+
755
+ def __deserialize_model(self, data, klass):
756
+ """Deserializes list or dict to model.
757
+
758
+ :param data: dict, list.
759
+ :param klass: class literal.
760
+ :return: model object.
761
+ """
762
+
763
+ return klass.from_dict(data)