jentic-openapi-parser 1.0.0a10__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,4 @@
1
+ Jentic OpenAPI Tools
2
+ Copyright (c) 2025 Jentic
3
+ Jentic OpenAPI Tools is licensed under Apache 2.0 license.
4
+ Copy of the Apache 2.0 license can be found in `LICENSE` file.
@@ -0,0 +1,291 @@
1
+ Metadata-Version: 2.4
2
+ Name: jentic-openapi-parser
3
+ Version: 1.0.0a10
4
+ Summary: Jentic OpenAPI Parser
5
+ Author: Jentic
6
+ Author-email: Jentic <hello@jentic.com>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ License-File: NOTICE
10
+ Requires-Dist: attrs~=25.4.0
11
+ Requires-Dist: jentic-openapi-common~=1.0.0a10
12
+ Requires-Dist: pyyaml~=6.0.3
13
+ Requires-Dist: requests~=2.32.5
14
+ Requires-Dist: ruamel-yaml~=0.18.15
15
+ Requires-Python: >=3.11
16
+ Project-URL: Homepage, https://github.com/jentic/jentic-openapi-tools
17
+ Description-Content-Type: text/markdown
18
+
19
+ # jentic-openapi-parser
20
+
21
+ A Python library for parsing OpenAPI documents using pluggable parser backends. This package is part of the Jentic OpenAPI Tools ecosystem and provides a flexible, extensible architecture for OpenAPI document parsing with support for multiple YAML/JSON parsing libraries.
22
+
23
+ ## Features
24
+
25
+ - **Pluggable Backend Architecture**: Support for multiple parsing strategies via entry points
26
+ - **Multiple Input Formats**: Parse OpenAPI documents from file URIs or text strings (JSON/YAML)
27
+ - **Multiple Parser Backends**: Choose from PyYAML, ruamel.yaml, or ruamel.yaml roundtrip modes
28
+ - **Enhanced JSON Serialization**: Built-in support for datetime, UUID, Path, Decimal, Enum, and attrs classes
29
+ - **Type Safety**: Full type hints with overloaded methods for precise return types
30
+ - **Extensible Design**: Easy integration of third-party parser backends
31
+
32
+ ## Installation
33
+
34
+ ```bash
35
+ pip install jentic-openapi-parser
36
+ ```
37
+
38
+ **Prerequisites:**
39
+ - Python 3.11+
40
+
41
+ ## Quick Start
42
+
43
+ ### Basic Parsing
44
+
45
+ ```python
46
+ from jentic.apitools.openapi.parser.core import OpenAPIParser
47
+
48
+ # Create parser with default backend (pyyaml)
49
+ parser = OpenAPIParser()
50
+
51
+ # Parse from file URI
52
+ doc = parser.parse("file:///path/to/openapi.yaml")
53
+ print(doc["info"]["title"])
54
+
55
+ # Parse from JSON string
56
+ json_doc = '{"openapi":"3.1.0","info":{"title":"My API","version":"1.0.0"}}'
57
+ doc = parser.parse(json_doc)
58
+
59
+ # Parse from YAML string
60
+ yaml_doc = """
61
+ openapi: 3.1.0
62
+ info:
63
+ title: My API
64
+ version: 1.0.0
65
+ """
66
+ doc = parser.parse(yaml_doc)
67
+ ```
68
+
69
+ ### Parse with Type Conversion
70
+
71
+ ```python
72
+ from ruamel.yaml import CommentedMap
73
+
74
+ # Parse with specific return type
75
+ parser = OpenAPIParser("ruamel-roundtrip")
76
+ doc = parser.parse(yaml_doc, return_type=CommentedMap)
77
+
78
+ # Parse with strict type checking
79
+ doc = parser.parse(yaml_doc, return_type=CommentedMap, strict=True)
80
+ ```
81
+
82
+ ### Using Different Backends
83
+
84
+ ```python
85
+ # Use PyYAML backend (default)
86
+ parser = OpenAPIParser("pyyaml")
87
+ doc = parser.parse("file:///path/to/openapi.yaml")
88
+
89
+ # Use ruamel.yaml backend (safe mode)
90
+ parser = OpenAPIParser("ruamel-safe")
91
+ doc = parser.parse("file:///path/to/openapi.yaml")
92
+
93
+ # Use ruamel.yaml roundtrip mode (preserves comments and formatting info)
94
+ parser = OpenAPIParser("ruamel-roundtrip")
95
+ doc = parser.parse("file:///path/to/openapi.yaml", return_type=CommentedMap)
96
+ # Access line/column information
97
+ print(doc.lc.line, doc.lc.col)
98
+ ```
99
+
100
+ ## Configuration Options
101
+
102
+ ### Backend Selection
103
+
104
+ ```python
105
+ # Use backend by name
106
+ parser = OpenAPIParser("pyyaml")
107
+
108
+ # Pass backend instance directly
109
+ from jentic.apitools.openapi.parser.backends.pyyaml import PyYAMLParserBackend
110
+ backend = PyYAMLParserBackend()
111
+ parser = OpenAPIParser(backend=backend)
112
+
113
+ # Pass backend class
114
+ parser = OpenAPIParser(backend=PyYAMLParserBackend)
115
+ ```
116
+
117
+ ### Custom Configuration
118
+
119
+ ```python
120
+ import logging
121
+
122
+ # Configure with custom logger and timeouts
123
+ logger = logging.getLogger(__name__)
124
+ parser = OpenAPIParser(
125
+ backend="pyyaml",
126
+ logger=logger,
127
+ conn_timeout=10, # Connection timeout in seconds
128
+ read_timeout=30 # Read timeout in seconds
129
+ )
130
+ ```
131
+
132
+ ## Working with Return Types
133
+
134
+ The parser supports flexible return type handling:
135
+
136
+ ```python
137
+ from ruamel.yaml import CommentedMap
138
+
139
+ parser = OpenAPIParser("ruamel-roundtrip")
140
+
141
+ # Without return_type: Returns plain dict
142
+ doc = parser.parse(yaml_doc)
143
+ assert isinstance(doc, dict)
144
+
145
+ # With return_type: Returns specified type
146
+ doc = parser.parse(yaml_doc, return_type=CommentedMap)
147
+ assert isinstance(doc, CommentedMap)
148
+
149
+ # With strict=True: Raises error if type doesn't match
150
+ try:
151
+ doc = parser.parse(yaml_doc, return_type=list, strict=True)
152
+ except TypeConversionError:
153
+ print("Type mismatch!")
154
+ ```
155
+
156
+ ## API Reference
157
+
158
+ ### OpenAPIParser
159
+
160
+ ```python
161
+ class OpenAPIParser:
162
+ def __init__(
163
+ self,
164
+ backend: str | BaseParserBackend | Type[BaseParserBackend] | None = None,
165
+ *,
166
+ logger: logging.Logger | None = None,
167
+ conn_timeout: int = 5,
168
+ read_timeout: int = 10,
169
+ ) -> None
170
+ ```
171
+
172
+ **Parameters:**
173
+ - `backend`: Parser backend to use. Can be:
174
+ - `str`: Name of a backend registered via entry points (e.g., "pyyaml", "ruamel-safe", "ruamel-roundtrip")
175
+ - `BaseParserBackend`: Instance of a parser backend
176
+ - `Type[BaseParserBackend]`: Class of a parser backend (will be instantiated)
177
+ - Defaults to `"pyyaml"` if `None`
178
+ - `logger`: Custom logger instance (optional)
179
+ - `conn_timeout`: Connection timeout in seconds for URI loading
180
+ - `read_timeout`: Read timeout in seconds for URI loading
181
+
182
+ **Methods:**
183
+
184
+ - `parse(document: str) -> dict[str, Any]`
185
+ - Parse without type conversion, returns plain dict
186
+
187
+ - `parse(document: str, *, return_type: type[T], strict: bool = False) -> T`
188
+ - Parse with optional type conversion
189
+ - `document`: File URI or text string (JSON/YAML)
190
+ - `return_type`: Expected return type (e.g., `dict`, `CommentedMap`)
191
+ - `strict`: If `True`, raises `TypeConversionError` if result doesn't match `return_type`
192
+ - Returns: Parsed document
193
+
194
+ - `load_uri(uri: str) -> str`
195
+ - Load content from a URI (HTTP(S), file://, or local file path)
196
+
197
+ - `list_backends() -> list[str]`
198
+ - Static method to list all available parser backends
199
+
200
+ ### JSON Serialization
201
+
202
+ The parser includes enhanced JSON serialization utilities for working with OpenAPI documents:
203
+
204
+ ```python
205
+ from jentic.apitools.openapi.parser.core import json_dumps
206
+
207
+ # Serialize with special type support
208
+ from datetime import datetime
209
+ from pathlib import Path
210
+ from uuid import UUID
211
+
212
+ data = {
213
+ "timestamp": datetime(2025, 10, 1, 12, 0, 0),
214
+ "id": UUID("550e8400-e29b-41d4-a716-446655440000"),
215
+ "path": Path("/var/log/app.log")
216
+ }
217
+
218
+ json_str = json_dumps(data, indent=2)
219
+ # Output:
220
+ # {
221
+ # "id": "550e8400-e29b-41d4-a716-446655440000",
222
+ # "path": "/var/log/app.log",
223
+ # "timestamp": "2025-10-01T12:00:00"
224
+ # }
225
+ ```
226
+
227
+ **Supported Types:**
228
+ - `datetime` / `date` - Serialized to ISO 8601 format
229
+ - `UUID` - Converted to string
230
+ - `Path` - Converted to string
231
+ - `Decimal` - Converted to float
232
+ - `Enum` - Serialized using enum value
233
+ - `attrs` classes - Converted to dictionaries
234
+
235
+ ### Exceptions
236
+
237
+ ```python
238
+ from jentic.apitools.openapi.parser.core.exceptions import (
239
+ OpenAPIParserError, # Base exception
240
+ DocumentParseError, # Parsing failed
241
+ DocumentLoadError, # URI loading failed
242
+ InvalidBackendError, # Backend initialization failed
243
+ BackendNotFoundError, # Backend not found
244
+ TypeConversionError, # Type conversion failed
245
+ )
246
+ ```
247
+
248
+ ## Available Backends
249
+
250
+ ### pyyaml (Default)
251
+ Standard PyYAML-based parser. Fast and reliable for basic parsing needs.
252
+
253
+ **Accepts:** `text` (JSON/YAML strings)
254
+
255
+ ```python
256
+ parser = OpenAPIParser("pyyaml")
257
+ doc = parser.parse(content)
258
+ ```
259
+
260
+ ### ruamel-safe
261
+ ruamel.yaml-based parser with safe loading. Provides better YAML 1.2 support than PyYAML.
262
+
263
+ **Accepts:** `text` (JSON/YAML strings), `uri` (file paths/URLs)
264
+
265
+ ```python
266
+ parser = OpenAPIParser("ruamel-safe")
267
+ doc = parser.parse(content)
268
+ ```
269
+
270
+ ### ruamel-roundtrip
271
+ ruamel.yaml roundtrip mode that preserves comments, formatting, and provides line/column information.
272
+
273
+ **Accepts:** `text` (JSON/YAML strings), `uri` (file paths/URLs)
274
+
275
+ ```python
276
+ from ruamel.yaml import CommentedMap
277
+
278
+ parser = OpenAPIParser("ruamel-roundtrip")
279
+ doc = parser.parse(content, return_type=CommentedMap)
280
+
281
+ # Access line/column information
282
+ print(f"Line: {doc.lc.line}, Column: {doc.lc.col}")
283
+ ```
284
+
285
+ ## Testing
286
+
287
+ Run the test suite:
288
+
289
+ ```bash
290
+ uv run --package jentic-openapi-parser pytest packages/jentic-openapi-parser -v
291
+ ```
@@ -0,0 +1,273 @@
1
+ # jentic-openapi-parser
2
+
3
+ A Python library for parsing OpenAPI documents using pluggable parser backends. This package is part of the Jentic OpenAPI Tools ecosystem and provides a flexible, extensible architecture for OpenAPI document parsing with support for multiple YAML/JSON parsing libraries.
4
+
5
+ ## Features
6
+
7
+ - **Pluggable Backend Architecture**: Support for multiple parsing strategies via entry points
8
+ - **Multiple Input Formats**: Parse OpenAPI documents from file URIs or text strings (JSON/YAML)
9
+ - **Multiple Parser Backends**: Choose from PyYAML, ruamel.yaml, or ruamel.yaml roundtrip modes
10
+ - **Enhanced JSON Serialization**: Built-in support for datetime, UUID, Path, Decimal, Enum, and attrs classes
11
+ - **Type Safety**: Full type hints with overloaded methods for precise return types
12
+ - **Extensible Design**: Easy integration of third-party parser backends
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ pip install jentic-openapi-parser
18
+ ```
19
+
20
+ **Prerequisites:**
21
+ - Python 3.11+
22
+
23
+ ## Quick Start
24
+
25
+ ### Basic Parsing
26
+
27
+ ```python
28
+ from jentic.apitools.openapi.parser.core import OpenAPIParser
29
+
30
+ # Create parser with default backend (pyyaml)
31
+ parser = OpenAPIParser()
32
+
33
+ # Parse from file URI
34
+ doc = parser.parse("file:///path/to/openapi.yaml")
35
+ print(doc["info"]["title"])
36
+
37
+ # Parse from JSON string
38
+ json_doc = '{"openapi":"3.1.0","info":{"title":"My API","version":"1.0.0"}}'
39
+ doc = parser.parse(json_doc)
40
+
41
+ # Parse from YAML string
42
+ yaml_doc = """
43
+ openapi: 3.1.0
44
+ info:
45
+ title: My API
46
+ version: 1.0.0
47
+ """
48
+ doc = parser.parse(yaml_doc)
49
+ ```
50
+
51
+ ### Parse with Type Conversion
52
+
53
+ ```python
54
+ from ruamel.yaml import CommentedMap
55
+
56
+ # Parse with specific return type
57
+ parser = OpenAPIParser("ruamel-roundtrip")
58
+ doc = parser.parse(yaml_doc, return_type=CommentedMap)
59
+
60
+ # Parse with strict type checking
61
+ doc = parser.parse(yaml_doc, return_type=CommentedMap, strict=True)
62
+ ```
63
+
64
+ ### Using Different Backends
65
+
66
+ ```python
67
+ # Use PyYAML backend (default)
68
+ parser = OpenAPIParser("pyyaml")
69
+ doc = parser.parse("file:///path/to/openapi.yaml")
70
+
71
+ # Use ruamel.yaml backend (safe mode)
72
+ parser = OpenAPIParser("ruamel-safe")
73
+ doc = parser.parse("file:///path/to/openapi.yaml")
74
+
75
+ # Use ruamel.yaml roundtrip mode (preserves comments and formatting info)
76
+ parser = OpenAPIParser("ruamel-roundtrip")
77
+ doc = parser.parse("file:///path/to/openapi.yaml", return_type=CommentedMap)
78
+ # Access line/column information
79
+ print(doc.lc.line, doc.lc.col)
80
+ ```
81
+
82
+ ## Configuration Options
83
+
84
+ ### Backend Selection
85
+
86
+ ```python
87
+ # Use backend by name
88
+ parser = OpenAPIParser("pyyaml")
89
+
90
+ # Pass backend instance directly
91
+ from jentic.apitools.openapi.parser.backends.pyyaml import PyYAMLParserBackend
92
+ backend = PyYAMLParserBackend()
93
+ parser = OpenAPIParser(backend=backend)
94
+
95
+ # Pass backend class
96
+ parser = OpenAPIParser(backend=PyYAMLParserBackend)
97
+ ```
98
+
99
+ ### Custom Configuration
100
+
101
+ ```python
102
+ import logging
103
+
104
+ # Configure with custom logger and timeouts
105
+ logger = logging.getLogger(__name__)
106
+ parser = OpenAPIParser(
107
+ backend="pyyaml",
108
+ logger=logger,
109
+ conn_timeout=10, # Connection timeout in seconds
110
+ read_timeout=30 # Read timeout in seconds
111
+ )
112
+ ```
113
+
114
+ ## Working with Return Types
115
+
116
+ The parser supports flexible return type handling:
117
+
118
+ ```python
119
+ from ruamel.yaml import CommentedMap
120
+
121
+ parser = OpenAPIParser("ruamel-roundtrip")
122
+
123
+ # Without return_type: Returns plain dict
124
+ doc = parser.parse(yaml_doc)
125
+ assert isinstance(doc, dict)
126
+
127
+ # With return_type: Returns specified type
128
+ doc = parser.parse(yaml_doc, return_type=CommentedMap)
129
+ assert isinstance(doc, CommentedMap)
130
+
131
+ # With strict=True: Raises error if type doesn't match
132
+ try:
133
+ doc = parser.parse(yaml_doc, return_type=list, strict=True)
134
+ except TypeConversionError:
135
+ print("Type mismatch!")
136
+ ```
137
+
138
+ ## API Reference
139
+
140
+ ### OpenAPIParser
141
+
142
+ ```python
143
+ class OpenAPIParser:
144
+ def __init__(
145
+ self,
146
+ backend: str | BaseParserBackend | Type[BaseParserBackend] | None = None,
147
+ *,
148
+ logger: logging.Logger | None = None,
149
+ conn_timeout: int = 5,
150
+ read_timeout: int = 10,
151
+ ) -> None
152
+ ```
153
+
154
+ **Parameters:**
155
+ - `backend`: Parser backend to use. Can be:
156
+ - `str`: Name of a backend registered via entry points (e.g., "pyyaml", "ruamel-safe", "ruamel-roundtrip")
157
+ - `BaseParserBackend`: Instance of a parser backend
158
+ - `Type[BaseParserBackend]`: Class of a parser backend (will be instantiated)
159
+ - Defaults to `"pyyaml"` if `None`
160
+ - `logger`: Custom logger instance (optional)
161
+ - `conn_timeout`: Connection timeout in seconds for URI loading
162
+ - `read_timeout`: Read timeout in seconds for URI loading
163
+
164
+ **Methods:**
165
+
166
+ - `parse(document: str) -> dict[str, Any]`
167
+ - Parse without type conversion, returns plain dict
168
+
169
+ - `parse(document: str, *, return_type: type[T], strict: bool = False) -> T`
170
+ - Parse with optional type conversion
171
+ - `document`: File URI or text string (JSON/YAML)
172
+ - `return_type`: Expected return type (e.g., `dict`, `CommentedMap`)
173
+ - `strict`: If `True`, raises `TypeConversionError` if result doesn't match `return_type`
174
+ - Returns: Parsed document
175
+
176
+ - `load_uri(uri: str) -> str`
177
+ - Load content from a URI (HTTP(S), file://, or local file path)
178
+
179
+ - `list_backends() -> list[str]`
180
+ - Static method to list all available parser backends
181
+
182
+ ### JSON Serialization
183
+
184
+ The parser includes enhanced JSON serialization utilities for working with OpenAPI documents:
185
+
186
+ ```python
187
+ from jentic.apitools.openapi.parser.core import json_dumps
188
+
189
+ # Serialize with special type support
190
+ from datetime import datetime
191
+ from pathlib import Path
192
+ from uuid import UUID
193
+
194
+ data = {
195
+ "timestamp": datetime(2025, 10, 1, 12, 0, 0),
196
+ "id": UUID("550e8400-e29b-41d4-a716-446655440000"),
197
+ "path": Path("/var/log/app.log")
198
+ }
199
+
200
+ json_str = json_dumps(data, indent=2)
201
+ # Output:
202
+ # {
203
+ # "id": "550e8400-e29b-41d4-a716-446655440000",
204
+ # "path": "/var/log/app.log",
205
+ # "timestamp": "2025-10-01T12:00:00"
206
+ # }
207
+ ```
208
+
209
+ **Supported Types:**
210
+ - `datetime` / `date` - Serialized to ISO 8601 format
211
+ - `UUID` - Converted to string
212
+ - `Path` - Converted to string
213
+ - `Decimal` - Converted to float
214
+ - `Enum` - Serialized using enum value
215
+ - `attrs` classes - Converted to dictionaries
216
+
217
+ ### Exceptions
218
+
219
+ ```python
220
+ from jentic.apitools.openapi.parser.core.exceptions import (
221
+ OpenAPIParserError, # Base exception
222
+ DocumentParseError, # Parsing failed
223
+ DocumentLoadError, # URI loading failed
224
+ InvalidBackendError, # Backend initialization failed
225
+ BackendNotFoundError, # Backend not found
226
+ TypeConversionError, # Type conversion failed
227
+ )
228
+ ```
229
+
230
+ ## Available Backends
231
+
232
+ ### pyyaml (Default)
233
+ Standard PyYAML-based parser. Fast and reliable for basic parsing needs.
234
+
235
+ **Accepts:** `text` (JSON/YAML strings)
236
+
237
+ ```python
238
+ parser = OpenAPIParser("pyyaml")
239
+ doc = parser.parse(content)
240
+ ```
241
+
242
+ ### ruamel-safe
243
+ ruamel.yaml-based parser with safe loading. Provides better YAML 1.2 support than PyYAML.
244
+
245
+ **Accepts:** `text` (JSON/YAML strings), `uri` (file paths/URLs)
246
+
247
+ ```python
248
+ parser = OpenAPIParser("ruamel-safe")
249
+ doc = parser.parse(content)
250
+ ```
251
+
252
+ ### ruamel-roundtrip
253
+ ruamel.yaml roundtrip mode that preserves comments, formatting, and provides line/column information.
254
+
255
+ **Accepts:** `text` (JSON/YAML strings), `uri` (file paths/URLs)
256
+
257
+ ```python
258
+ from ruamel.yaml import CommentedMap
259
+
260
+ parser = OpenAPIParser("ruamel-roundtrip")
261
+ doc = parser.parse(content, return_type=CommentedMap)
262
+
263
+ # Access line/column information
264
+ print(f"Line: {doc.lc.line}, Column: {doc.lc.col}")
265
+ ```
266
+
267
+ ## Testing
268
+
269
+ Run the test suite:
270
+
271
+ ```bash
272
+ uv run --package jentic-openapi-parser pytest packages/jentic-openapi-parser -v
273
+ ```
@@ -0,0 +1,41 @@
1
+ [project]
2
+ name = "jentic-openapi-parser"
3
+ version = "1.0.0-alpha.10"
4
+ description = "Jentic OpenAPI Parser"
5
+ readme = "README.md"
6
+ authors = [{ name = "Jentic", email = "hello@jentic.com" }]
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE", "NOTICE"]
9
+ requires-python = ">=3.11"
10
+ dependencies = [
11
+ "attrs~=25.4.0",
12
+ "jentic-openapi-common~=1.0.0-alpha.10",
13
+ "pyyaml~=6.0.3",
14
+ "requests~=2.32.5",
15
+ "ruamel-yaml~=0.18.15"
16
+ ]
17
+
18
+ [project.urls]
19
+ Homepage = "https://github.com/jentic/jentic-openapi-tools"
20
+
21
+ [tool.uv]
22
+ package = true
23
+
24
+ [tool.uv.build-backend]
25
+ namespace = true
26
+ module-name = "jentic.apitools.openapi.parser"
27
+ module-root = "src/"
28
+
29
+ [tool.uv.sources]
30
+ jentic-openapi-common = { workspace = true }
31
+
32
+ [build-system]
33
+ requires = ["uv_build~=0.8.15"]
34
+ build-backend = "uv_build"
35
+
36
+ [project.entry-points."jentic.apitools.openapi.parser.backends"]
37
+ base = "jentic.apitools.openapi.parser.backends.base:BaseParserBackend"
38
+ pyyaml = "jentic.apitools.openapi.parser.backends.pyyaml:PyYAMLParserBackend"
39
+ ruamel-safe = "jentic.apitools.openapi.parser.backends.ruamel_safe:RuamelSafeParserBackend"
40
+ ruamel-roundtrip = "jentic.apitools.openapi.parser.backends.ruamel_roundtrip:RuamelRoundTripParserBackend"
41
+
@@ -0,0 +1,29 @@
1
+ import logging
2
+ from abc import ABC, abstractmethod
3
+ from collections.abc import Sequence
4
+ from typing import Any
5
+
6
+
7
+ __all__ = ["BaseParserBackend"]
8
+
9
+
10
+ class BaseParserBackend(ABC):
11
+ """Interface that all Parser backends must implement."""
12
+
13
+ @abstractmethod
14
+ def parse(self, document: str, *, logger: logging.Logger | None = None) -> Any:
15
+ """Parses an OpenAPI document given by URI or file path or text.
16
+ Returns a dict."""
17
+ ...
18
+
19
+ @staticmethod
20
+ @abstractmethod
21
+ def accepts() -> Sequence[str]:
22
+ """Return a sequence of input formats this backend can handle.
23
+
24
+ Returns:
25
+ Sequence of supported input formats. Common values:
26
+ - "uri": Accepts URI/file path references
27
+ - "text": Accepts string (JSON/YAML) representation
28
+ """
29
+ ...
@@ -0,0 +1,50 @@
1
+ import logging
2
+ from collections.abc import Sequence
3
+ from typing import Literal, Mapping
4
+
5
+ import yaml
6
+
7
+ from jentic.apitools.openapi.common.uri import is_uri_like
8
+ from jentic.apitools.openapi.parser.backends.base import BaseParserBackend
9
+ from jentic.apitools.openapi.parser.core.loader import load_uri
10
+
11
+
12
+ __all__ = ["PyYAMLParserBackend"]
13
+
14
+
15
+ class PyYAMLParserBackend(BaseParserBackend):
16
+ def parse(self, document: str, *, logger: logging.Logger | None = None) -> dict:
17
+ logger = logger or logging.getLogger(__name__)
18
+ if is_uri_like(document):
19
+ return self._parse_uri(document, logger)
20
+ return self._parse_text(document, logger)
21
+
22
+ @staticmethod
23
+ def accepts() -> Sequence[Literal["uri", "text"]]:
24
+ """Return supported input formats.
25
+
26
+ Returns:
27
+ Sequence of supported document format identifiers:
28
+ - "uri": File path or URI pointing to OpenAPI Document
29
+ - "text": String (JSON/YAML) representation
30
+ """
31
+ return ["uri", "text"]
32
+
33
+ def _parse_uri(self, uri: str, logger: logging.Logger) -> dict:
34
+ logger.debug("Starting download of %s", uri)
35
+ return self._parse_text(load_uri(uri, 5, 10, logger), logger)
36
+
37
+ def _parse_text(self, text: str, logger: logging.Logger) -> dict:
38
+ if not isinstance(text, (bytes, str)):
39
+ raise TypeError(f"Unsupported document type: {type(text)!r}")
40
+
41
+ if isinstance(text, bytes):
42
+ text = text.decode()
43
+
44
+ data = yaml.safe_load(text)
45
+ logger.debug("Document successfully parsed")
46
+
47
+ if not isinstance(data, Mapping):
48
+ raise TypeError(f"Parsed document is not a mapping: {type(data)!r}")
49
+
50
+ return dict(data)
@@ -0,0 +1,9 @@
1
+ from jentic.apitools.openapi.parser.backends.ruamel_safe import RuamelSafeParserBackend
2
+
3
+
4
+ __all__ = ["RuamelRoundTripParserBackend"]
5
+
6
+
7
+ class RuamelRoundTripParserBackend(RuamelSafeParserBackend):
8
+ def __init__(self, pure: bool = True):
9
+ super().__init__(typ="rt", pure=pure)
@@ -0,0 +1,54 @@
1
+ import logging
2
+ from collections.abc import Sequence
3
+ from typing import Literal, Mapping
4
+
5
+ from ruamel.yaml import YAML, CommentedMap
6
+
7
+ from jentic.apitools.openapi.common.uri import is_uri_like
8
+ from jentic.apitools.openapi.parser.backends.base import BaseParserBackend
9
+ from jentic.apitools.openapi.parser.core.loader import load_uri
10
+
11
+
12
+ __all__ = ["RuamelSafeParserBackend"]
13
+
14
+
15
+ class RuamelSafeParserBackend(BaseParserBackend):
16
+ def __init__(self, typ: str = "safe", pure: bool = True):
17
+ self.yaml = YAML(typ=typ, pure=pure)
18
+ self.yaml.default_flow_style = False
19
+
20
+ def parse(self, document: str, *, logger: logging.Logger | None = None) -> CommentedMap:
21
+ logger = logger or logging.getLogger(__name__)
22
+ if is_uri_like(document):
23
+ return self._parse_uri(document, logger)
24
+ return self._parse_text(document, logger)
25
+
26
+ @staticmethod
27
+ def accepts() -> Sequence[Literal["uri", "text"]]:
28
+ """Return supported input formats.
29
+
30
+ Returns:
31
+ Sequence of supported document format identifiers:
32
+ - "uri": File path or URI pointing to OpenAPI Document
33
+ - "text": String (JSON/YAML) representation
34
+ """
35
+ return ["uri", "text"]
36
+
37
+ def _parse_uri(self, uri: str, logger: logging.Logger) -> CommentedMap:
38
+ logger.debug("Starting download of %s", uri)
39
+ return self._parse_text(load_uri(uri, 5, 10, logger), logger)
40
+
41
+ def _parse_text(self, text: str, logger: logging.Logger) -> CommentedMap:
42
+ if not isinstance(text, (bytes, str)):
43
+ raise TypeError(f"Unsupported document type: {type(text)!r}")
44
+
45
+ if isinstance(text, bytes):
46
+ text = text.decode()
47
+
48
+ data: CommentedMap = self.yaml.load(text)
49
+ logger.debug("YAML document successfully parsed")
50
+
51
+ if not isinstance(data, Mapping):
52
+ raise TypeError(f"Parsed YAML document is not a mapping: {type(data)!r}")
53
+
54
+ return data
@@ -0,0 +1,27 @@
1
+ from .exceptions import (
2
+ BackendNotFoundError,
3
+ DocumentLoadError,
4
+ DocumentParseError,
5
+ InvalidBackendError,
6
+ OpenAPIParserError,
7
+ TypeConversionError,
8
+ )
9
+ from .loader import load_uri
10
+ from .openapi_parser import OpenAPIParser
11
+ from .serialization import json_dumps
12
+
13
+
14
+ __all__ = [
15
+ "OpenAPIParser",
16
+ # URI utilities
17
+ "load_uri",
18
+ # Serialization
19
+ "json_dumps",
20
+ # Parser exceptions
21
+ "OpenAPIParserError",
22
+ "DocumentParseError",
23
+ "DocumentLoadError",
24
+ "TypeConversionError",
25
+ "InvalidBackendError",
26
+ "BackendNotFoundError",
27
+ ]
@@ -0,0 +1,29 @@
1
+ """
2
+ OpenAPI Parser exceptions.
3
+
4
+ This module defines all custom exceptions used by the OpenAPI parser.
5
+ """
6
+
7
+
8
+ class OpenAPIParserError(Exception):
9
+ """Base exception for OpenAPI parser errors."""
10
+
11
+
12
+ class InvalidBackendError(OpenAPIParserError):
13
+ """Raised when an invalid backend is provided."""
14
+
15
+
16
+ class BackendNotFoundError(InvalidBackendError):
17
+ """Raised when a named backend cannot be found."""
18
+
19
+
20
+ class DocumentParseError(OpenAPIParserError):
21
+ """Raised when parsing fails."""
22
+
23
+
24
+ class DocumentLoadError(OpenAPIParserError):
25
+ """Raised when document loading fails."""
26
+
27
+
28
+ class TypeConversionError(OpenAPIParserError):
29
+ """Raised when type conversion fails in strict mode."""
@@ -0,0 +1,45 @@
1
+ """Document loading utilities for OpenAPI parser."""
2
+
3
+ import logging
4
+
5
+ import requests
6
+
7
+ from jentic.apitools.openapi.common.uri import is_file_uri, is_http_https_url, resolve_to_absolute
8
+
9
+ from .exceptions import DocumentLoadError
10
+
11
+
12
+ __all__ = ["load_uri"]
13
+
14
+
15
+ def load_uri(
16
+ uri: str, conn_timeout: int, read_timeout: int, logger: logging.Logger | None = None
17
+ ) -> str:
18
+ logger = logger or logging.getLogger(__name__)
19
+ resolved_uri = resolve_to_absolute(uri)
20
+ content = ""
21
+
22
+ try:
23
+ if is_http_https_url(resolved_uri):
24
+ logger.info("Loading URI %s", resolved_uri)
25
+ resp = requests.get(resolved_uri, timeout=(conn_timeout, read_timeout))
26
+ logger.info(
27
+ "Load of URI %s completed, status: %s, content length: %s",
28
+ resolved_uri,
29
+ resp.status_code,
30
+ len(resp.content),
31
+ )
32
+ content = resp.text
33
+ elif is_file_uri(resolved_uri):
34
+ logger.info("Loading local file %s", resolved_uri)
35
+ with open(resolved_uri, "r", encoding="utf-8") as f:
36
+ content = f.read()
37
+ else:
38
+ # Treat as local file path
39
+ logger.info("Loading local file %s", resolved_uri)
40
+ with open(resolved_uri, "r", encoding="utf-8") as f:
41
+ content = f.read()
42
+ except Exception as e:
43
+ raise DocumentLoadError(f"Failed to load URI '{uri}': {e}") from e
44
+
45
+ return content
@@ -0,0 +1,206 @@
1
+ import importlib.metadata
2
+ import logging
3
+ import warnings
4
+ from typing import Any, Mapping, Optional, Sequence, Type, TypeVar, cast, overload
5
+
6
+ from jentic.apitools.openapi.common.uri import is_uri_like
7
+ from jentic.apitools.openapi.parser.backends.base import BaseParserBackend
8
+
9
+ from .exceptions import (
10
+ BackendNotFoundError,
11
+ DocumentParseError,
12
+ InvalidBackendError,
13
+ OpenAPIParserError,
14
+ TypeConversionError,
15
+ )
16
+ from .loader import load_uri
17
+
18
+
19
+ __all__ = ["OpenAPIParser"]
20
+
21
+
22
+ # Cache entry points at module level for performance
23
+ try:
24
+ _PARSER_BACKENDS = {
25
+ ep.name: ep
26
+ for ep in importlib.metadata.entry_points(group="jentic.apitools.openapi.parser.backends")
27
+ }
28
+ except Exception as e:
29
+ warnings.warn(f"Failed to load parser backend entry points: {e}", RuntimeWarning)
30
+ _PARSER_BACKENDS = {}
31
+
32
+ T = TypeVar("T")
33
+
34
+
35
+ class OpenAPIParser:
36
+ """
37
+ Provides a parser for OpenAPI specifications using customizable backends.
38
+
39
+ This class is designed to facilitate the parsing of OpenAPI documents.
40
+ It supports one backend at a time and can be extended through backends.
41
+
42
+ Attributes:
43
+ backend: Backend used by the parser implementing the BaseParserBackend interface.
44
+ logger: Logger instance.
45
+ conn_timeout: Connection timeout in seconds.
46
+ read_timeout: Read timeout in seconds.
47
+ """
48
+
49
+ def __init__(
50
+ self,
51
+ backend: str | BaseParserBackend | Type[BaseParserBackend] | None = None,
52
+ *,
53
+ logger: logging.Logger | None = None,
54
+ conn_timeout: int = 5,
55
+ read_timeout: int = 10,
56
+ ):
57
+ logger = logger or logging.getLogger(__name__)
58
+ backend = backend if backend else "pyyaml"
59
+ self.backend: BaseParserBackend
60
+ self.logger = logger
61
+ self.conn_timeout = conn_timeout
62
+ self.read_timeout = read_timeout
63
+
64
+ if isinstance(backend, str):
65
+ try:
66
+ if backend in _PARSER_BACKENDS:
67
+ try:
68
+ logger.debug(f"using parser backend '{backend}'")
69
+ backend_class = _PARSER_BACKENDS[backend].load() # loads the class
70
+ self.backend = backend_class()
71
+ except Exception as e:
72
+ raise InvalidBackendError(
73
+ f"Failed to load parser backend '{backend}': {e}"
74
+ ) from e
75
+ else:
76
+ logger.error(f"No parser backend named '{backend}' found")
77
+ raise BackendNotFoundError(f"No parser backend named '{backend}' found")
78
+ except OpenAPIParserError:
79
+ raise
80
+ except Exception as e:
81
+ raise InvalidBackendError(f"Error initializing backend '{backend}': {e}") from e
82
+
83
+ elif isinstance(backend, BaseParserBackend):
84
+ logger.debug(f"using parser backend '{type[backend]}'")
85
+ self.backend = backend
86
+ elif isinstance(backend, type) and issubclass(backend, BaseParserBackend):
87
+ try:
88
+ # class (not instance) is passed
89
+ self.backend = backend()
90
+ logger.debug(f"using parser backend '{type[backend]}'")
91
+ except Exception as e:
92
+ raise InvalidBackendError(
93
+ f"Failed to instantiate backend class '{backend.__name__}': {e}"
94
+ ) from e
95
+
96
+ else:
97
+ logger.error("Invalid backend type: must be name or backend class/instance")
98
+ raise InvalidBackendError(
99
+ "Invalid backend type: must be a backend name (str), "
100
+ "BaseParserBackend instance, or BaseParserBackend class"
101
+ )
102
+
103
+ @overload
104
+ def parse(self, document: str) -> dict[str, Any]: ...
105
+
106
+ @overload
107
+ def parse(self, document: str, *, return_type: type[T], strict: bool = False) -> T: ...
108
+
109
+ def parse(
110
+ self, document: str, *, return_type: type[T] | None = None, strict: bool = False
111
+ ) -> Any:
112
+ try:
113
+ raw = self._parse(document)
114
+ except OpenAPIParserError:
115
+ raise
116
+ except Exception as e:
117
+ raise DocumentParseError(f"Unexpected error during parsing: {e}") from e
118
+
119
+ if return_type is None:
120
+ return self._to_plain(raw)
121
+
122
+ if strict:
123
+ if not isinstance(raw, return_type):
124
+ msg = f"Expected {getattr(return_type, '__name__', return_type)}, got {type(raw).__name__}"
125
+ self.logger.error(msg)
126
+ raise TypeConversionError(msg)
127
+ return cast(T, raw)
128
+
129
+ def _parse(self, document: str) -> Any:
130
+ document_is_uri = is_uri_like(document)
131
+ backend_document: str | None = None
132
+
133
+ self.logger.debug(f"parsing a '{'uri' if document_is_uri else 'text'}'")
134
+
135
+ if document_is_uri and "uri" in self.backend.accepts():
136
+ backend_document = document # Delegate loading to backend
137
+ elif document_is_uri and "text" in self.backend.accepts():
138
+ backend_document = self.load_uri(document)
139
+ elif not document_is_uri and "text" in self.backend.accepts():
140
+ backend_document = document
141
+
142
+ if backend_document is None:
143
+ accepted_formats = ", ".join(self.backend.accepts())
144
+ document_type = "URI" if document_is_uri else "text"
145
+ raise DocumentParseError(
146
+ f"Backend '{type(self.backend).__name__}' does not accept {document_type} format. "
147
+ f"Accepted formats: {accepted_formats}"
148
+ )
149
+
150
+ try:
151
+ parse_result = self.backend.parse(backend_document, logger=self.logger)
152
+ except Exception as e:
153
+ # Log the original error and wrap it
154
+ msg = f"Failed to parse document with backend '{type(self.backend).__name__}': {e}"
155
+ self.logger.error(msg)
156
+ raise DocumentParseError(msg) from e
157
+
158
+ if parse_result is None:
159
+ msg = "No valid document found"
160
+ self.logger.error(msg)
161
+ raise DocumentParseError(msg)
162
+
163
+ return parse_result
164
+
165
+ def has_non_uri_backend(self) -> bool:
166
+ """Check if any backend accepts 'text' but not 'uri'."""
167
+ accepted = self.backend.accepts()
168
+ return "text" in accepted and "uri" not in accepted
169
+
170
+ def _to_plain(self, value: Any) -> Any:
171
+ # Mapping
172
+ if isinstance(value, Mapping):
173
+ return {k: self._to_plain(v) for k, v in value.items()}
174
+
175
+ # Sequence but NOT str/bytes
176
+ if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
177
+ return [self._to_plain(x) for x in value]
178
+
179
+ # Scalar
180
+ return value
181
+
182
+ @staticmethod
183
+ def is_uri_like(s: Optional[str]) -> bool:
184
+ return is_uri_like(s)
185
+
186
+ def load_uri(self, uri: str) -> str:
187
+ return load_uri(uri, self.conn_timeout, self.read_timeout, self.logger)
188
+
189
+ @staticmethod
190
+ def list_backends() -> list[str]:
191
+ """
192
+ List all available parser backends registered via entry points.
193
+
194
+ This static method discovers and returns the names of all parser backends
195
+ that have been registered in the 'jentic.apitools.openapi.parser.backends'
196
+ entry point group.
197
+
198
+ Returns:
199
+ List of backend names that can be used when initializing OpenAPIParser.
200
+
201
+ Example:
202
+ >>> backends = OpenAPIParser.list_backends()
203
+ >>> print(backends)
204
+ ['pyyaml', 'ruamel']
205
+ """
206
+ return list(_PARSER_BACKENDS.keys())
@@ -0,0 +1,2 @@
1
+ # marker file for type checkers
2
+
@@ -0,0 +1,88 @@
1
+ import json
2
+ from datetime import date, datetime
3
+ from decimal import Decimal
4
+ from enum import Enum
5
+ from pathlib import Path
6
+ from typing import Any, cast
7
+ from uuid import UUID
8
+
9
+ import attrs
10
+
11
+
12
+ __all__ = ["json_dumps", "CustomEncoder"]
13
+
14
+
15
+ class CustomEncoder(json.JSONEncoder):
16
+ """JSON encoder with extended type support for OpenAPI documents.
17
+
18
+ Extends the standard json.JSONEncoder to handle additional Python types
19
+ commonly found in OpenAPI documents and related data structures.
20
+
21
+ Supported types:
22
+ - datetime/date: Serialized using ISO 8601 format
23
+ - UUID: Converted to string representation
24
+ - Path: Converted to string representation
25
+ - Decimal: Converted to float
26
+ - Enum: Serialized using the enum value
27
+ - attrs classes: Converted to dictionaries using attrs.asdict()
28
+ """
29
+
30
+ def default(self, o):
31
+ """Serialize special types not handled by the default JSON encoder.
32
+
33
+ Args:
34
+ o: Object to serialize
35
+
36
+ Returns:
37
+ JSON-serializable representation of the object
38
+
39
+ Raises:
40
+ TypeError: If the object type is not supported
41
+ """
42
+ if isinstance(o, (datetime, date)):
43
+ return o.isoformat()
44
+ if isinstance(o, (UUID, Path)):
45
+ return str(o)
46
+ if isinstance(o, Decimal):
47
+ return float(o)
48
+ if isinstance(o, Enum):
49
+ return o.value
50
+ if attrs.has(o):
51
+ return attrs.asdict(cast(Any, o))
52
+ return super().default(o)
53
+
54
+
55
+ def json_dumps(
56
+ data: Any, indent: int | None = None, *, cls: type[json.JSONEncoder] = CustomEncoder
57
+ ) -> str:
58
+ """Serialize data to a JSON string with extended type support.
59
+
60
+ This function provides JSON serialization with automatic handling of
61
+ datetime, Path, UUID, Decimal, Enum, and attrs-decorated classes.
62
+ The output is UTF-8 compatible with sorted keys for consistency.
63
+
64
+ Args:
65
+ data: The data to serialize (dict, list, or any JSON-compatible type)
66
+ indent: Number of spaces for indentation. None for compact output.
67
+ cls: Custom JSON encoder class. Defaults to CustomEncoder.
68
+
69
+ Returns:
70
+ A JSON string representation of the data
71
+
72
+ Raises:
73
+ TypeError: If the data contains unsupported types
74
+
75
+ Example:
76
+ >>> from datetime import datetime
77
+ >>> data = {"timestamp": datetime.now(), "count": 42}
78
+ >>> json_str = json_dumps(data, indent=2)
79
+ """
80
+ return json.dumps(
81
+ data,
82
+ indent=indent,
83
+ ensure_ascii=False,
84
+ allow_nan=False,
85
+ sort_keys=True,
86
+ separators=(",", ":") if indent is None else (",", ": "),
87
+ cls=cls,
88
+ )