ds-protocol-graphql-py-lib 0.1.0a1__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,32 @@
1
+ """
2
+ **File:** ``__init__.py``
3
+ **Region:** ``ds-protocol-graphql-py-lib``
4
+
5
+ Description
6
+ -----------
7
+ A Python package from the ds-protocol-graphql-py-lib library.
8
+
9
+ Example
10
+ -------
11
+ .. code-block:: python
12
+
13
+ from ds_protocol_graphql_py_lib import __version__
14
+
15
+ print(f"Package version: {__version__}")
16
+ """
17
+
18
+ from importlib.metadata import version
19
+
20
+ from ds_protocol_graphql_py_lib.serde.deserializer import GraphqlDeserializer
21
+
22
+ from .dataset import GraphqlDataset, GraphqlDatasetSettings
23
+
24
+ PACKAGE_NAME = "ds-protocol-graphql-py-lib"
25
+ __version__ = version(PACKAGE_NAME)
26
+
27
+ __all__ = [
28
+ "GraphqlDataset",
29
+ "GraphqlDatasetSettings",
30
+ "GraphqlDeserializer",
31
+ "__version__",
32
+ ]
@@ -0,0 +1,31 @@
1
+ """
2
+ **File:** ``__init__.py``
3
+ **Region:** ``ds_protocol_graphql_py_lib/dataset``
4
+
5
+ Package initialization for GraphQL dataset module.
6
+
7
+ Example:
8
+ >>> from ds_protocol_graphql_py_lib.dataset import GraphqlDataset, GraphqlDatasetSettings
9
+ >>> from ds_protocol_http_py_lib import HttpLinkedService, HttpLinkedServiceSettings
10
+ >>> linked_service = HttpLinkedService(
11
+ ... settings=HttpLinkedServiceSettings(host="https://api.example.graphql/graphql"),
12
+ ... id="service-id",
13
+ ... name="graphql_service",
14
+ ... version="1.0.0",
15
+ ... )
16
+ >>> dataset = GraphqlDataset(
17
+ ... linked_service=linked_service,
18
+ ... settings=GraphqlDatasetSettings(url="https://api.example.graphql/graphql"),
19
+ ... id="dataset-id",
20
+ ... name="graphql_dataset",
21
+ ... version="1.0.0",
22
+ ... )
23
+ """
24
+
25
+ from .graphql import GraphqlDataset, GraphqlDatasetSettings, GraphqlReadSettings
26
+
27
+ __all__ = [
28
+ "GraphqlDataset",
29
+ "GraphqlDatasetSettings",
30
+ "GraphqlReadSettings",
31
+ ]
@@ -0,0 +1,558 @@
1
+ """
2
+ **File:** ``graphql.py``
3
+ **Region:** ``ds_protocol_graphql_py_lib/dataset``
4
+
5
+ GraphQL dataset implementation for CRUD operations via GraphQL API.
6
+
7
+ Example:
8
+ >>> linked_service = HttpLinkedService(
9
+ ... settings=HttpLinkedServiceSettings(
10
+ ... host="https://api.example.graphql/graphql",
11
+ ... auth_type=AuthType.NO_AUTH,
12
+ ... ),
13
+ ... id="service-id",
14
+ ... name="graphql_service",
15
+ ... version="1.0.0",
16
+ ... )
17
+ >>> dataset = GraphqlDataset(
18
+ ... linked_service=linked_service,
19
+ ... settings=GraphqlDatasetSettings(
20
+ ... url="https://api.example.graphql/graphql",
21
+ ... read=GraphqlReadSettings(
22
+ ... query="{ users { id name email } }"
23
+ ... ),
24
+ ... ),
25
+ ... id="dataset-id",
26
+ ... name="graphql_dataset",
27
+ ... version="1.0.0",
28
+ ... )
29
+ >>> dataset.read()
30
+ """
31
+
32
+ from dataclasses import dataclass, field
33
+ from typing import Any, Generic, NoReturn, TypeVar
34
+
35
+ import pandas as pd # type: ignore[import-untyped]
36
+ from ds_common_logger_py_lib import Logger
37
+ from ds_common_serde_py_lib import Serializable
38
+ from ds_protocol_http_py_lib.dataset.http import HttpLinkedServiceType
39
+ from ds_resource_plugin_py_lib.common.resource.dataset import (
40
+ DatasetSettings,
41
+ DatasetStorageFormatType,
42
+ TabularDataset,
43
+ )
44
+ from ds_resource_plugin_py_lib.common.resource.dataset.errors import (
45
+ CreateError,
46
+ DeleteError,
47
+ ListError,
48
+ ReadError,
49
+ )
50
+ from ds_resource_plugin_py_lib.common.resource.errors import NotSupportedError
51
+ from ds_resource_plugin_py_lib.common.resource.linked_service.errors import (
52
+ ConnectionError,
53
+ )
54
+ from ds_resource_plugin_py_lib.common.serde.serialize import PandasSerializer
55
+
56
+ from ..enums import ResourceType
57
+ from ..serde.deserializer import GraphqlDeserializer
58
+
59
+ logger = Logger.get_logger(__name__, package=True)
60
+
61
+
62
+ @dataclass(kw_only=True)
63
+ class GraphqlReadSettings(Serializable):
64
+ """Settings specific to reading data from GraphQL API."""
65
+
66
+ query: str
67
+ """ The GraphQL query string to execute for reading data.
68
+ This should be a valid GraphQL query that the endpoint can execute to return the desired data.
69
+ For example: "{ users { id name email } }"
70
+ """
71
+ variables: dict[str, Any] | None = None
72
+ """ Optional variables to include with the GraphQL query."""
73
+ operation_name: str | None = None
74
+ """ Optional operation name for the GraphQL query, used when the query contains multiple operations."""
75
+
76
+
77
+ @dataclass(kw_only=True)
78
+ class GraphqlDeleteSettings(Serializable):
79
+ """Settings specific to deleting data from GraphQL API."""
80
+
81
+ mutation: str
82
+ """ The GraphQL mutation string to execute for deleting data."""
83
+ identity_columns: list[str]
84
+ """ The list of column names in the input DataFrame that uniquely identify the rows to delete."""
85
+ variables: dict[str, Any] | None = None
86
+ """ Optional variables to include with the GraphQL mutation."""
87
+ operation_name: str | None = None
88
+ """ Optional operation name for the GraphQL mutation, used when the mutation contains multiple operations."""
89
+
90
+
91
+ @dataclass(kw_only=True)
92
+ class GraphqlCreateSettings(Serializable):
93
+ """Settings specific to creating data in GraphQL API."""
94
+
95
+ mutation: str
96
+ """ The GraphQL mutation string to execute for creating data.
97
+ This should be a valid GraphQL mutation that the endpoint can execute to create new records based on the input data.
98
+ For example: "mutation CreateUser($input: CreateUserInput!) { createUser(input: $input) { id name email } }"
99
+ """
100
+ input_field: str # The field name for input variables (e.g., "input")
101
+ """ The name of the variable in the GraphQL mutation that will receive the input data."""
102
+ operation_name: str | None = None
103
+ """ Optional operation name for the GraphQL mutation, used when the mutation contains multiple operations."""
104
+
105
+
106
+ @dataclass(kw_only=True)
107
+ class GraphqlDatasetSettings(DatasetSettings):
108
+ url: str
109
+ """The URL of the GraphQL endpoint to connect to. This is the base URL where the GraphQL API is hosted."""
110
+ primary_keys: list[str] | None = None
111
+ """Optional list of column names that serve as primary keys for the dataset.
112
+ This can be used for operations that require unique identification of rows."""
113
+ headers: dict[str, str] | None = None
114
+ """Optional HTTP headers to include in requests to the GraphQL endpoint, such as authentication tokens or content type."""
115
+ read: GraphqlReadSettings | None = None
116
+ """Settings for read operations."""
117
+ delete: GraphqlDeleteSettings | None = None
118
+ """Settings for delete operations."""
119
+ create: GraphqlCreateSettings | None = None
120
+ """Settings for create operations."""
121
+
122
+
123
+ GraphqlDatasetSettingsType = TypeVar(
124
+ "GraphqlDatasetSettingsType",
125
+ bound=GraphqlDatasetSettings,
126
+ )
127
+
128
+
129
+ @dataclass(kw_only=True)
130
+ class GraphqlDataset(
131
+ TabularDataset[
132
+ HttpLinkedServiceType,
133
+ GraphqlDatasetSettingsType,
134
+ PandasSerializer,
135
+ GraphqlDeserializer,
136
+ ],
137
+ Generic[HttpLinkedServiceType, GraphqlDatasetSettingsType],
138
+ ):
139
+ """
140
+ Represent Graphql dataset.
141
+ """
142
+
143
+ settings: GraphqlDatasetSettingsType
144
+ linked_service: HttpLinkedServiceType
145
+
146
+ deserializer: GraphqlDeserializer | None = field(
147
+ default_factory=lambda: GraphqlDeserializer(format=DatasetStorageFormatType.JSON),
148
+ )
149
+
150
+ @property
151
+ def type(self) -> ResourceType:
152
+ return ResourceType.DATASET
153
+
154
+ @property
155
+ def supports_checkpoint(self) -> bool:
156
+ """
157
+ Indicate whether this provider supports incremental loads via checkpointing.
158
+
159
+ GraphQL provider does not yet support checkpoint-based incremental loads.
160
+ All reads are full loads.
161
+
162
+ Returns:
163
+ False, indicating checkpointing is not supported.
164
+ """
165
+ return False
166
+
167
+ def read(self) -> None:
168
+ """
169
+ Read Graphql dataset.
170
+
171
+ Sends a GraphQL query to the endpoint with the query, variables, and operation name
172
+ specified in settings.read. Populates self.output with the result as a DataFrame.
173
+
174
+ Handles various GraphQL response patterns via GraphqlDeserializer:
175
+ - Direct arrays: {"data": {"users": [...]}}
176
+ - Relay connections: {"data": {"users": {"edges": [{"node": {...}}]}}}
177
+ - Single objects: {"data": {"user": {...}}}
178
+
179
+ Returns:
180
+ None. The result is stored in self.output as a DataFrame.
181
+
182
+ Raises:
183
+ ConnectionError: If the linked service connection is not initialized.
184
+ ReadError: If read settings are not provided or if the GraphQL query fails.
185
+ """
186
+ if self.linked_service.connection is None:
187
+ raise ConnectionError(message="Connection is not initialized.") from None
188
+
189
+ if not self.settings.read:
190
+ raise ReadError("GraphQL read settings must be provided in settings.read")
191
+
192
+ if not self.deserializer:
193
+ raise ReadError("Deserializer is not configured for GraphQL dataset")
194
+
195
+ try:
196
+ payload: dict[str, Any] = {
197
+ "query": self.settings.read.query,
198
+ }
199
+
200
+ if self.settings.read.variables:
201
+ payload["variables"] = self.settings.read.variables
202
+
203
+ if self.settings.read.operation_name:
204
+ payload["operationName"] = self.settings.read.operation_name
205
+
206
+ result = self.linked_service.connection.session.post(
207
+ url=self.settings.url,
208
+ json=payload,
209
+ headers=self.settings.headers,
210
+ )
211
+
212
+ result.raise_for_status()
213
+ response_data = result.json()
214
+
215
+ self._check_for_graphql_read_error(response_data)
216
+ self.output = self.deserializer.deserialize_graphql(response_data)
217
+
218
+ except ReadError:
219
+ raise
220
+ except Exception as e:
221
+ raise ReadError(
222
+ message=f"Failed to read from GraphQL: {e!s}",
223
+ details={"url": self.settings.url},
224
+ ) from e
225
+
226
+ @staticmethod
227
+ def _check_for_graphql_read_error(response_data: dict[str, Any]) -> None:
228
+ if "errors" in response_data:
229
+ base_message = "GraphQL query failed"
230
+
231
+ errors = response_data["errors"]
232
+
233
+ # Safely extract a human-readable message from the first error, if available.
234
+ if isinstance(errors, list) and errors:
235
+ first_error = errors[0]
236
+ if isinstance(first_error, dict):
237
+ error_message = first_error.get("message")
238
+ if isinstance(error_message, str) and error_message:
239
+ base_message = f"{base_message}: {error_message}"
240
+ elif isinstance(errors, dict):
241
+ error_message = errors.get("message")
242
+ if isinstance(error_message, str) and error_message:
243
+ base_message = f"{base_message}: {error_message}"
244
+
245
+ raise ReadError(
246
+ message=base_message,
247
+ details={"errors": errors},
248
+ )
249
+
250
+ def create(self) -> None:
251
+ """
252
+ Create new rows in the GraphQL endpoint using mutations.
253
+
254
+ Sends all rows in a single atomic GraphQL mutation request.
255
+ Populates self.output with the created rows.
256
+
257
+ Returns:
258
+ None. The result is stored in self.output as a DataFrame.
259
+
260
+ Raises:
261
+ ConnectionError: If the linked service connection is not initialized.
262
+ CreateError: If create settings are not provided or if the GraphQL mutation fails.
263
+ """
264
+ # Per DATASET_CONTRACT: empty input is a no-op
265
+ if self.input is None or len(self.input) == 0:
266
+ self.output = self.input.copy() if self.input is not None else pd.DataFrame()
267
+ return
268
+
269
+ if self.settings.create is None:
270
+ raise CreateError("Create settings must be provided in settings.create")
271
+
272
+ if not self.deserializer:
273
+ raise CreateError("Deserializer is not configured for GraphQL dataset")
274
+
275
+ self._validate_create_settings()
276
+
277
+ try:
278
+ rows_data = self.input.to_dict(orient="records")
279
+ input_value = rows_data[0] if len(rows_data) == 1 else rows_data
280
+
281
+ variables = {self.settings.create.input_field: input_value}
282
+
283
+ payload: dict[str, Any] = {"query": self.settings.create.mutation}
284
+ if variables:
285
+ payload["variables"] = variables
286
+ if self.settings.create.operation_name:
287
+ payload["operationName"] = self.settings.create.operation_name
288
+
289
+ result = self.linked_service.connection.session.post(
290
+ url=self.settings.url,
291
+ json=payload,
292
+ headers=self.settings.headers,
293
+ )
294
+
295
+ result.raise_for_status()
296
+ response_data = result.json()
297
+
298
+ if "errors" in response_data:
299
+ raise CreateError(
300
+ message="GraphQL create mutation failed",
301
+ details={
302
+ "input_data": rows_data,
303
+ "errors": response_data.get("errors"),
304
+ },
305
+ )
306
+
307
+ if "data" in response_data:
308
+ df_result = self.deserializer.deserialize_graphql(response_data)
309
+ self.output = df_result if not df_result.empty else self.input.copy()
310
+ else:
311
+ self.output = self.input.copy()
312
+
313
+ except CreateError:
314
+ raise
315
+ except Exception as e:
316
+ raise CreateError(
317
+ message=f"Failed to create rows via GraphQL: {e!s}",
318
+ details={
319
+ "url": self.settings.url,
320
+ "input_field": self.settings.create.input_field,
321
+ "row_count": len(self.input),
322
+ },
323
+ ) from e
324
+
325
+ def update(self) -> None:
326
+ """
327
+ Update entity using Graphql.
328
+ """
329
+ raise NotSupportedError("Update operation is not supported for Graphql dataset")
330
+
331
+ def upsert(self) -> None:
332
+ """
333
+ Upsert entity using Graphql.
334
+ """
335
+ raise NotSupportedError("Upsert operation is not supported for Graphql dataset")
336
+
337
+ def delete(self) -> None: # noqa: PLR0912
338
+ """
339
+ Delete specific rows from the GraphQL endpoint using mutations.
340
+
341
+ Sends all rows in a single atomic GraphQL mutation request.
342
+ Populates self.output with the deleted rows.
343
+
344
+ Returns:
345
+ None. The result is stored in self.output as a DataFrame.
346
+
347
+ Raises:
348
+ ConnectionError: If the linked service connection is not initialized.
349
+ DeleteError: If delete settings are not provided, if identity columns are missing, or if the GraphQL mutation fails.
350
+ """
351
+ # Per DATASET_CONTRACT: empty input is a no-op
352
+ if self.input is None or len(self.input) == 0:
353
+ self.output = self.input.copy() if self.input is not None else pd.DataFrame()
354
+ return
355
+
356
+ if self.linked_service.connection is None:
357
+ raise ConnectionError(message="Connection is not initialized.") from None
358
+
359
+ if not self.settings.delete:
360
+ raise DeleteError("GraphQL delete settings must be provided in settings.delete")
361
+
362
+ if not self.deserializer:
363
+ raise DeleteError("Deserializer is not configured for GraphQL dataset")
364
+
365
+ for col in self.settings.delete.identity_columns:
366
+ if col not in self.input.columns:
367
+ raise DeleteError(
368
+ message=f"Identity column '{col}' not found in input",
369
+ details={"available_columns": list(self.input.columns)},
370
+ )
371
+
372
+ try:
373
+ rows_data = self.input.to_dict(orient="records")
374
+ variables = {}
375
+
376
+ if len(rows_data) == 1:
377
+ # Single row: extract identity values
378
+ row = rows_data[0]
379
+ for col in self.settings.delete.identity_columns:
380
+ variables[col] = row[col]
381
+ else:
382
+ # Multiple rows: build array for each identity column
383
+ for col in self.settings.delete.identity_columns:
384
+ variables[col] = [row[col] for row in rows_data]
385
+
386
+ if self.settings.delete.variables:
387
+ variables.update(self.settings.delete.variables)
388
+
389
+ # Build GraphQL request payload
390
+ payload: dict[str, Any] = {
391
+ "query": self.settings.delete.mutation,
392
+ }
393
+
394
+ if variables:
395
+ payload["variables"] = variables
396
+
397
+ if self.settings.delete.operation_name:
398
+ payload["operationName"] = self.settings.delete.operation_name
399
+
400
+ # Execute the mutation (single atomic request)
401
+ result = self.linked_service.connection.session.post(
402
+ url=self.settings.url,
403
+ json=payload,
404
+ headers=self.settings.headers,
405
+ )
406
+
407
+ result.raise_for_status()
408
+ response_data = result.json()
409
+
410
+ if "errors" in response_data:
411
+ raise DeleteError(
412
+ message="GraphQL delete mutation failed",
413
+ details={
414
+ "input_data": rows_data,
415
+ "errors": response_data.get("errors"),
416
+ },
417
+ )
418
+
419
+ if "data" in response_data:
420
+ df_result = self.deserializer.deserialize_graphql(response_data)
421
+ self.output = df_result if not df_result.empty else self.input.copy()
422
+ else:
423
+ self.output = self.input.copy()
424
+
425
+ except DeleteError:
426
+ raise
427
+ except Exception as e:
428
+ raise DeleteError(
429
+ message=f"Failed to delete rows via GraphQL: {e!s}",
430
+ details={
431
+ "url": self.settings.url,
432
+ "identity_columns": self.settings.delete.identity_columns,
433
+ "row_count": len(self.input),
434
+ },
435
+ ) from e
436
+
437
+ def purge(self) -> NoReturn:
438
+ """
439
+ Purge entity using Graphql.
440
+ """
441
+ raise NotSupportedError("Purge operation is not supported for Graphql dataset")
442
+
443
+ def rename(self) -> NoReturn:
444
+ """
445
+ Rename entity using Graphql.
446
+ """
447
+ raise NotSupportedError("Rename operation is not supported for Graphql dataset")
448
+
449
+ def list(self) -> None:
450
+ """
451
+ Discover available resources in the GraphQL schema via introspection.
452
+
453
+ Executes a GraphQL introspection query to fetch all available queries
454
+ and their arguments from the schema. Populates self.output with a DataFrame
455
+ containing resource metadata (name, type, description, etc.).
456
+
457
+ Returns:
458
+ None. The result is stored in self.output as a DataFrame.
459
+
460
+ Raises:
461
+ ConnectionError: If the linked service connection is not initialized.
462
+ ListError: If the GraphQL introspection query fails.
463
+ """
464
+ if self.linked_service.connection is None:
465
+ raise ConnectionError(message="Connection is not initialized.") from None
466
+
467
+ client = self.linked_service.connection
468
+
469
+ # GraphQL introspection query to discover all queries
470
+ introspection_query = """
471
+ query IntrospectionQuery {
472
+ __schema {
473
+ queryType {
474
+ name
475
+ fields {
476
+ name
477
+ description
478
+ args {
479
+ name
480
+ type {
481
+ name
482
+ kind
483
+ }
484
+ }
485
+ }
486
+ }
487
+ }
488
+ }
489
+ """
490
+
491
+ try:
492
+ result = client.session.post(
493
+ url=self.settings.url,
494
+ json={"query": introspection_query},
495
+ headers=self.settings.headers,
496
+ )
497
+
498
+ result.raise_for_status()
499
+ response_data = result.json()
500
+
501
+ if "errors" in response_data:
502
+ raise ListError(
503
+ message="GraphQL introspection query failed",
504
+ details={"errors": response_data.get("errors")},
505
+ )
506
+
507
+ # Extract query fields from the introspection response
508
+ query_type = response_data.get("data", {}).get("__schema", {}).get("queryType", {})
509
+ fields = query_type.get("fields", [])
510
+
511
+ resources = []
512
+ for field in fields:
513
+ arg_names = [arg.get("name") for arg in field.get("args", [])]
514
+ resources.append(
515
+ {
516
+ "name": field.get("name"),
517
+ "type": "query",
518
+ "description": field.get("description") or "",
519
+ "arguments": ", ".join(arg_names) if arg_names else None,
520
+ "arg_count": len(arg_names),
521
+ }
522
+ )
523
+
524
+ self.output = pd.DataFrame(resources)
525
+
526
+ except Exception as e:
527
+ raise ListError(
528
+ message=f"Failed to list GraphQL schema resources: {e!s}",
529
+ details={"url": self.settings.url},
530
+ ) from e
531
+
532
+ def close(self) -> None:
533
+ """
534
+ Just to satisfy the contract - GraphQL dataset does not maintain persistent connections that require cleanup.
535
+
536
+ Returns:
537
+ None
538
+ """
539
+ pass
540
+
541
+ def _validate_create_settings(self) -> None:
542
+ """
543
+ Validate create settings are properly configured.
544
+
545
+ Returns:
546
+ None: if settings are valid.
547
+
548
+ Raises:
549
+ CreateError: If any required create settings are missing or invalid.
550
+ """
551
+ if self.linked_service.connection is None:
552
+ raise ConnectionError(message="Connection is not initialized.") from None
553
+ if not self.settings.create:
554
+ raise CreateError("GraphQL create settings must be provided in settings.create")
555
+ if not self.settings.create.mutation:
556
+ raise CreateError("GraphQL mutation must be provided in settings.create.mutation")
557
+ if not self.settings.create.input_field:
558
+ raise CreateError("Input field name must be provided in settings.create.input_field")
@@ -0,0 +1,20 @@
1
+ """
2
+ **File:** ``enums.py``
3
+ **Region:** ``ds_protocol_graphql_py_lib/enums``
4
+
5
+ Constants for GRAPHQL protocol.
6
+
7
+ Example:
8
+ >>> ResourceType.DATASET
9
+ 'ds.resource.dataset.graphql'
10
+ """
11
+
12
+ from enum import StrEnum
13
+
14
+
15
+ class ResourceType(StrEnum):
16
+ """
17
+ Constants for GRAPHQL protocol.
18
+ """
19
+
20
+ DATASET = "ds.resource.dataset.graphql"
File without changes
@@ -0,0 +1,10 @@
1
+ package-name: graphql
2
+ name: graphql
3
+ description: GRAPHQL protocol for the DS Business Workflow
4
+
5
+ dataset:
6
+ - name: GRAPHQL
7
+ type: ds.resource.dataset.graphql
8
+ version: 1.0.0
9
+ description: GRAPHQL dataset
10
+ class_name: ds_protocol_graphql_py_lib.dataset.graphql.GraphqlDataset
@@ -0,0 +1,16 @@
1
+ """
2
+ **File:** ``__init__.py``
3
+ **Region:** ``ds_protocol_graphql_py_lib/serde``
4
+
5
+ Serialization and deserialization utilities for GraphQL protocol.
6
+
7
+ Example:
8
+ >>> from ds_protocol_graphql_py_lib.serde import GraphqlDeserializer
9
+ >>> deserializer = GraphqlDeserializer()
10
+ """
11
+
12
+ from .deserializer import GraphqlDeserializer
13
+
14
+ __all__ = [
15
+ "GraphqlDeserializer",
16
+ ]
@@ -0,0 +1,127 @@
1
+ """
2
+ **File:** ``deserializer.py``
3
+ **Region:** ``ds_protocol_graphql_py_lib/serde``
4
+
5
+ GraphQL response deserializer for converting GraphQL responses to DataFrames.
6
+
7
+ Example:
8
+ >>> from ds_protocol_graphql_py_lib import GraphqlDeserializer
9
+ >>> deserializer = GraphqlDeserializer(format=DatasetStorageFormatType.JSON)
10
+ >>> response = {"data": {"users": [{"id": "1", "name": "John"}]}}
11
+ >>> df = deserializer.deserialize(response)
12
+ """
13
+
14
+ from typing import Any
15
+
16
+ import pandas as pd # type: ignore[import-untyped]
17
+ from ds_resource_plugin_py_lib.common.serde.deserialize import PandasDeserializer
18
+
19
+
20
+ class GraphqlDeserializer(PandasDeserializer):
21
+ """
22
+ Deserializer for GraphQL API responses.
23
+
24
+ Handles various GraphQL response patterns:
25
+ - Direct arrays: {"data": {"users": [...]}}
26
+ - Relay connections: {"data": {"users": {"edges": [{"node": {...}}]}}}
27
+ - Single objects: {"data": {"user": {...}}}
28
+ - Introspection queries: {"data": {"__type": {"fields": [...]}}}
29
+ """
30
+
31
+ def deserialize_graphql(self, data: Any) -> pd.DataFrame:
32
+ """
33
+ Deserialize GraphQL response to pandas DataFrame.
34
+
35
+ Args:
36
+ data: GraphQL response dict or raw data
37
+
38
+ Returns:
39
+ DataFrame containing the extracted data
40
+ """
41
+ if not isinstance(data, dict):
42
+ return pd.DataFrame()
43
+
44
+ extracted_data = data.get("data", data)
45
+
46
+ return self._parse_graphql_data(extracted_data)
47
+
48
+ def _parse_graphql_data(self, data: Any) -> pd.DataFrame:
49
+ """
50
+ Parse GraphQL data structure into DataFrame.
51
+
52
+ Handles nested structures and various GraphQL response patterns.
53
+
54
+ Args:
55
+ data: The data portion of the GraphQL response
56
+
57
+ Returns:
58
+ DataFrame with the extracted data
59
+ """
60
+ if data is None:
61
+ return pd.DataFrame()
62
+
63
+ if isinstance(data, list):
64
+ return pd.DataFrame(data)
65
+
66
+ if not isinstance(data, dict):
67
+ return pd.DataFrame([data])
68
+
69
+ if len(data) == 1:
70
+ nested_value = next(iter(data.values()))
71
+
72
+ # Nested value is a list - use it
73
+ if isinstance(nested_value, list):
74
+ return pd.DataFrame(nested_value)
75
+
76
+ # Nested value has edges (Relay pagination)
77
+ if isinstance(nested_value, dict) and "edges" in nested_value:
78
+ return self._extract_relay_nodes(nested_value)
79
+
80
+ # Check if it's a pure container with only array fields
81
+ if isinstance(nested_value, dict):
82
+ return self._handle_nested_dict(nested_value)
83
+
84
+ # Handle Relay pagination at top level
85
+ if "edges" in data:
86
+ return self._extract_relay_nodes(data)
87
+
88
+ return pd.DataFrame([data])
89
+
90
+ def _handle_nested_dict(self, nested_value: dict[str, Any]) -> pd.DataFrame:
91
+ """
92
+ Handle nested dict - determine if it's a pure array container or single object.
93
+
94
+ Args:
95
+ nested_value: The nested dictionary to analyze
96
+
97
+ Returns:
98
+ DataFrame with appropriate data extraction
99
+ """
100
+ all_values = list(nested_value.values())
101
+ list_fields = [v for v in all_values if isinstance(v, list)]
102
+ non_list_fields = [v for v in all_values if not isinstance(v, list) and v is not None]
103
+
104
+ # Pure container with single array field (e.g., GraphQL introspection)
105
+ # Example: {"fields": [...]} where ALL non-null values are the single list
106
+ if len(list_fields) == 1 and len(non_list_fields) == 0:
107
+ return pd.DataFrame(list_fields[0])
108
+
109
+ # Single object with mixed fields - keep as single row
110
+ return pd.DataFrame([nested_value])
111
+
112
+ def _extract_relay_nodes(self, data: dict[str, Any]) -> pd.DataFrame:
113
+ """
114
+ Extract nodes from Relay-style pagination structure.
115
+
116
+ Args:
117
+ data: Dict containing "edges" key with Relay pagination structure
118
+
119
+ Returns:
120
+ DataFrame with nodes extracted from edges
121
+ """
122
+ edges = data.get("edges", [])
123
+ if not isinstance(edges, list):
124
+ return pd.DataFrame()
125
+
126
+ nodes = [edge.get("node", edge) for edge in edges if edge]
127
+ return pd.DataFrame(nodes)
@@ -0,0 +1,141 @@
1
+ Metadata-Version: 2.4
2
+ Name: ds-protocol-graphql-py-lib
3
+ Version: 0.1.0a1
4
+ Summary: A Python package from the DS library collection
5
+ Author-email: Grasp Labs AS <hello@grasplabs.com>
6
+ Maintainer-email: Grasp Labs AS <hello@grasplabs.com>
7
+ License-Expression: Apache-2.0
8
+ Project-URL: Documentation, https://grasp-labs.github.io/ds-protocol-graphql-py-lib/
9
+ Project-URL: Repository, https://github.com/grasp-labs/ds-protocol-graphql-py-lib/
10
+ Project-URL: Issues, https://github.com/grasp-labs/ds-protocol-graphql-py-lib/issues/
11
+ Project-URL: Changelog, https://github.com/grasp-labs/ds-protocol-graphql-py-lib/releases
12
+ Keywords: ds,python
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Intended Audience :: Developers
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Requires-Python: >=3.11
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE-APACHE
24
+ Requires-Dist: ds-resource-plugin-py-lib<1.0.0,>=0.1.0rc3
25
+ Requires-Dist: ds-protocol-http-py-lib<1.0.0,>=0.1.0b5
26
+ Requires-Dist: ds-common-serde-py-lib<1.0.0,>=0.1.0b1
27
+ Requires-Dist: requests<3.0.0,>=2.32.0
28
+ Provides-Extra: dev
29
+ Requires-Dist: ruff>=0.1.8; extra == "dev"
30
+ Requires-Dist: mypy>=1.7.0; extra == "dev"
31
+ Requires-Dist: pytest>=7.4.0; extra == "dev"
32
+ Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
33
+ Requires-Dist: pytest-xdist>=3.3.0; extra == "dev"
34
+ Requires-Dist: pre-commit>=3.6.0; extra == "dev"
35
+ Requires-Dist: build>=1.0.0; extra == "dev"
36
+ Requires-Dist: twine>=4.0.0; extra == "dev"
37
+ Requires-Dist: sphinx>=7.1.0; extra == "dev"
38
+ Requires-Dist: sphinx-autoapi>=3.0.0; extra == "dev"
39
+ Requires-Dist: sphinx-material>=0.0.35; extra == "dev"
40
+ Requires-Dist: bandit>=1.7.0; extra == "dev"
41
+ Provides-Extra: test
42
+ Requires-Dist: pytest>=7.4.0; extra == "test"
43
+ Requires-Dist: pytest-cov>=4.1.0; extra == "test"
44
+ Requires-Dist: pytest-xdist>=3.3.0; extra == "test"
45
+ Provides-Extra: docs
46
+ Requires-Dist: sphinx>=7.1.0; extra == "docs"
47
+ Requires-Dist: sphinx-autoapi>=3.0.0; extra == "docs"
48
+ Requires-Dist: sphinx-material>=0.0.35; extra == "docs"
49
+ Dynamic: license-file
50
+
51
+ # ds-protocol-graphql-py-lib
52
+
53
+ A Python package from the ds-common library collection.
54
+
55
+ ## Installation
56
+
57
+ Install the package using pip:
58
+
59
+ ```bash
60
+ pip install ds-protocol-graphql-py-lib
61
+ ```
62
+
63
+ Or using uv (recommended):
64
+
65
+ ```bash
66
+ uv pip install ds-protocol-graphql-py-lib
67
+ ```
68
+
69
+ ## Quick Start
70
+
71
+ ```python
72
+ from ds_protocol_graphql_py_lib import __version__
73
+
74
+ print(f"ds-protocol-graphql-py-lib version: {__version__}")
75
+ ```
76
+
77
+ ## Features
78
+
79
+ <!-- List your package features here -->
80
+ - Feature 1: Description of feature 1
81
+ - Feature 2: Description of feature 2
82
+ - Feature 3: Description of feature 3
83
+
84
+ ## Usage
85
+
86
+ <!-- Add usage examples here -->
87
+
88
+ ```python
89
+ # Example usage
90
+ import ds_protocol_graphql_py_lib
91
+
92
+ # Your code examples here
93
+ ```
94
+
95
+ ## Requirements
96
+
97
+ - Python 3.9 or higher
98
+ - <!-- List any required dependencies -->
99
+
100
+ ## Optional Dependencies
101
+
102
+ <!-- List optional dependencies if any -->
103
+ - Optional dependency 1: Description
104
+ - Optional dependency 2: Description
105
+
106
+ ## Documentation
107
+
108
+ Full documentation is available at:
109
+
110
+ - [GitHub Repository](https://github.com/grasp-labs/ds-protocol-graphql-py-lib)
111
+ - [Documentation Site](https://grasp-labs.github.io/ds-protocol-graphql-py-lib/)
112
+
113
+ ## Development
114
+
115
+ To contribute or set up a development environment:
116
+
117
+ ```bash
118
+ # Clone the repository
119
+ git clone https://github.com/grasp-labs/ds-protocol-graphql-py-lib.git
120
+ cd ds-protocol-graphql-py-lib
121
+
122
+ # Install development dependencies
123
+ uv sync --all-extras --dev
124
+
125
+ # Run tests
126
+ make test
127
+ ```
128
+
129
+ See the [README](https://github.com/grasp-labs/ds-protocol-graphql-py-lib#readme)
130
+ for more information.
131
+
132
+ ## License
133
+
134
+ This package is licensed under the Apache License 2.0.
135
+ See the [LICENSE-APACHE](https://github.com/grasp-labs/ds-protocol-graphql-py-lib/blob/main/LICENSE-APACHE)
136
+ file for details.
137
+
138
+ ## Support
139
+
140
+ - **Issues**: [GitHub Issues](https://github.com/grasp-labs/ds-protocol-graphql-py-lib/issues)
141
+ - **Releases**: [GitHub Releases](https://github.com/grasp-labs/ds-protocol-graphql-py-lib/releases)
@@ -0,0 +1,14 @@
1
+ ds_protocol_graphql_py_lib/__init__.py,sha256=zt1gSEbAmYOzZI6MKC5b6HjQJMB2Bf8cK09nilantP0,680
2
+ ds_protocol_graphql_py_lib/enums.py,sha256=raB_NDgksvuSjiwGf31pLOOgstNAQLLP66H29ndU7II,340
3
+ ds_protocol_graphql_py_lib/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ ds_protocol_graphql_py_lib/resource.yaml,sha256=TIJxTcdR6-4v_4O2-aTzygobMKa1HSXTPv_jCyJlmGo,287
5
+ ds_protocol_graphql_py_lib/dataset/__init__.py,sha256=iLJPNzVLggfFzkHc7MRAFlESNgFTHOnlD_RRigAh7u0,1015
6
+ ds_protocol_graphql_py_lib/dataset/graphql.py,sha256=bz2hzo59e1icCDUA27Bx9WTkuTOkWfAp1mYeeskbJkw,20444
7
+ ds_protocol_graphql_py_lib/serde/__init__.py,sha256=RGN0_KB6rbbGqcKWllvf_BRywTsOGFYs1jSO9B5NcF0,367
8
+ ds_protocol_graphql_py_lib/serde/deserializer.py,sha256=vdH2OOMdxlKTcZGd4mx3yHp0z--7eCqipudmOPxaSz8,4263
9
+ ds_protocol_graphql_py_lib-0.1.0a1.dist-info/licenses/LICENSE-APACHE,sha256=x7hTayZVCUk-5lPVLtNK2GqkOEpbWLlu5Zf9IoSUvPg,11234
10
+ ds_protocol_graphql_py_lib-0.1.0a1.dist-info/METADATA,sha256=7ylykF8Gre0HAlidlj8tTnSfJWfD4dPB1I54l38Tda8,4259
11
+ ds_protocol_graphql_py_lib-0.1.0a1.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
12
+ ds_protocol_graphql_py_lib-0.1.0a1.dist-info/entry_points.txt,sha256=k_lg_wtafcsZfHO8s0xQWZnlmXHSoeIUFsk6FQZwyqs,52
13
+ ds_protocol_graphql_py_lib-0.1.0a1.dist-info/top_level.txt,sha256=Td1KsvO2Ioz63w_EZOu68RxMzhS4BC_bg7ctMZ-z7D4,27
14
+ ds_protocol_graphql_py_lib-0.1.0a1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [ds.protocols]
2
+ graphql = ds_protocol_graphql_py_lib
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets \"[]\"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same \"printed page\" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2025] [Aider AS]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the \"License\");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an \"AS IS\" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ ds_protocol_graphql_py_lib