datasette-plugin-router 0.0.1a2__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,289 @@
1
+ from __future__ import annotations
2
+ import inspect
3
+ import re
4
+ from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, get_args, get_origin, Annotated
5
+ from dataclasses import dataclass
6
+
7
+
8
+ @dataclass
9
+ class Route:
10
+ path: str
11
+ method: str
12
+ fn: Optional[Callable]
13
+ output: Optional[type]
14
+ input_schema: Optional[Dict[str, Any]] = None
15
+ output_schema: Optional[Dict[str, Any]] = None
16
+
17
+ T = TypeVar('T')
18
+
19
+
20
+ class Body:
21
+ """Marker for request body parameters.
22
+
23
+ Usage:
24
+ from typing import Annotated
25
+
26
+ async def view(params: Annotated[InputModel, Body()]):
27
+ # params is properly typed as InputModel
28
+ # and at runtime, Body() marker tells router to parse request body
29
+
30
+ The recommended pattern is to use typing.Annotated for full type safety.
31
+ For backwards compatibility, Body[Model] syntax is still supported.
32
+ """
33
+
34
+ def __init__(self, model: Optional[type[T]] = None):
35
+ self.model = model
36
+
37
+ def __repr__(self) -> str: # helpful for debugging
38
+ if self.model:
39
+ try:
40
+ name = getattr(self.model, "__name__", repr(self.model))
41
+ except Exception:
42
+ name = repr(self.model)
43
+ return f"Body[{name}]"
44
+ return "Body()"
45
+
46
+ @classmethod
47
+ def __class_getitem__(cls, item: type[T]) -> "Body":
48
+ """Allow writing `Body[Model]` in annotations (backwards compatibility).
49
+
50
+ Python will call this at import-time for subscription expressions
51
+ (PEP 560). We return an instance of `Body` so that runtime code
52
+ can continue to use `isinstance(param.annotation, Body)`.
53
+ """
54
+ return cls(item)
55
+
56
+ class Router:
57
+ """Minimal router to simplify Datasette plugin route registration and OpenAPI export."""
58
+
59
+ def __init__(self, title: str = "API", version: str = "0.0.0", server_url: str = "http://localhost:8001") -> None:
60
+ self._routes: List[Route] = []
61
+ self.title = title
62
+ self.version = version
63
+ self.server_url = server_url
64
+
65
+ def POST(self, path: str, *, output: Optional[type] = None):
66
+ return self._add_route("post", path, output=output)
67
+
68
+ def GET(self, path: str, *, output: Optional[type] = None):
69
+ return self._add_route("get", path, output=output)
70
+
71
+ def _add_route(self, method: str, path: str, *, output: Optional[type]):
72
+ def decorator(fn: Callable):
73
+ # create route entry and compute/store input/output schemas now so
74
+ # we don't need to keep references to the original function
75
+ entry = Route(path=path, output=output, method=method, fn=None)
76
+ input_model = None
77
+ # inspect the handler's annotations for Body[...] parameters or Annotated[..., Body()]
78
+ try:
79
+ for _, param in inspect.signature(fn).parameters.items():
80
+ # Check for Annotated[Model, Body()] pattern
81
+ if get_origin(param.annotation) is Annotated:
82
+ args = get_args(param.annotation)
83
+ if len(args) >= 2:
84
+ # args[0] is the actual type, args[1:] are metadata
85
+ for metadata in args[1:]:
86
+ if isinstance(metadata, Body):
87
+ input_model = args[0]
88
+ break
89
+ if input_model:
90
+ break
91
+ # Check for backwards-compatible Body[Model] pattern
92
+ elif isinstance(param.annotation, Body):
93
+ input_model = param.annotation.model
94
+ break
95
+ except Exception:
96
+ input_model = None
97
+
98
+ if input_model is not None:
99
+ entry.input_schema = _model_to_schema(input_model) or {"type": "object"}
100
+
101
+ # determine output schema from explicit `output` if provided
102
+ if entry.output is not None:
103
+ entry.output_schema = _model_to_schema(entry.output) or {"type": "object"}
104
+
105
+ # append entry after computing schemas
106
+ self._routes.append(entry)
107
+
108
+ async def view(request, datasette=None, scope=None, receive=None, send=None):
109
+ declared_kwargs = inspect.signature(fn).parameters
110
+ kwargs = {}
111
+ for name, param in declared_kwargs.items():
112
+ if name == "request":
113
+ kwargs["request"] = request
114
+ continue
115
+ elif name == "datasette":
116
+ kwargs["datasette"] = datasette
117
+ continue
118
+ elif name == "scope":
119
+ kwargs["scope"] = scope
120
+ continue
121
+ elif name == "receive":
122
+ kwargs["receive"] = receive
123
+ continue
124
+ elif name == "send":
125
+ kwargs["send"] = send
126
+ continue
127
+
128
+ # Check for Annotated[Model, Body()] pattern
129
+ body_model = None
130
+ if get_origin(param.annotation) is Annotated:
131
+ args = get_args(param.annotation)
132
+ if len(args) >= 2:
133
+ for metadata in args[1:]:
134
+ if isinstance(metadata, Body):
135
+ body_model = args[0]
136
+ break
137
+ # Check for backwards-compatible Body[Model] pattern
138
+ elif isinstance(param.annotation, Body):
139
+ body_model = param.annotation.model
140
+
141
+ if body_model is not None:
142
+ data = await request.post_body()
143
+ model_instance = body_model.model_validate_json(data) # type: ignore[attr-defined]
144
+ kwargs[name] = model_instance
145
+ continue
146
+
147
+ # see if the str parameter exists in `request.url_vars`.
148
+ if param.annotation is str:
149
+ kwargs[name] = request.url_vars[name]
150
+ continue
151
+
152
+ return await fn(**kwargs)
153
+
154
+ # replace the stored fn with the wrapper that Datasette should call
155
+ entry.fn = view
156
+ return view
157
+
158
+ return decorator
159
+
160
+ def routes(self) -> List[Tuple[str, Callable]]:
161
+ """Return a list of (regex, view_fn) tuples suitable for Datasette's register_routes."""
162
+ out: List[Tuple[str, Callable]] = []
163
+ for entry in self._routes:
164
+ if entry.fn is not None:
165
+ out.append((entry.path, entry.fn))
166
+ return out
167
+
168
+ def openapi_document_json(self) -> Dict[str, Any]:
169
+ """Return a minimal OpenAPI 3 document as a Python dict."""
170
+ components_schemas: Dict[str, Any] = {}
171
+
172
+ doc: Dict[str, Any] = {
173
+ "openapi": "3.0.0",
174
+ "info": {"title": self.title, "version": self.version},
175
+ "servers": [{"url": self.server_url}],
176
+ "paths": {},
177
+ }
178
+
179
+ for entry in self._routes:
180
+ path = entry.path
181
+ openapi_path = _regex_to_openapi_path(path)
182
+ method = entry.method.lower()
183
+
184
+ parameters: List[Dict[str, Any]] = []
185
+ for name in _extract_named_groups(path):
186
+ parameters.append({"name": name, "in": "path", "required": True, "schema": {"type": "string"}})
187
+
188
+ operation: Dict[str, Any] = {"responses": {"200": {"description": "OK"}}, "parameters": parameters}
189
+
190
+ # Use precomputed schemas stored on the Route entry
191
+ if entry.input_schema is not None:
192
+ # Extract $defs and rewrite $refs for OpenAPI 3.0 compatibility
193
+ processed_schema = _extract_defs_from_schema(entry.input_schema, components_schemas)
194
+ operation["requestBody"] = {"required": True, "content": {"application/json": {"schema": processed_schema}}}
195
+
196
+ if entry.output is not None:
197
+ schema = _model_to_schema(entry.output) or {"type": "object"}
198
+ # Extract $defs and rewrite $refs for OpenAPI 3.0 compatibility
199
+ processed_schema = _extract_defs_from_schema(schema, components_schemas)
200
+ operation["responses"]["200"]["content"] = {"application/json": {"schema": processed_schema}}
201
+
202
+ doc["paths"].setdefault(openapi_path, {})[method] = operation
203
+
204
+ # Add components.schemas if any $defs were extracted
205
+ if components_schemas:
206
+ doc["components"] = {"schemas": components_schemas}
207
+
208
+ return doc
209
+
210
+ def _model_to_schema(model: type) -> Optional[Dict[str, Any]]:
211
+ if model is None:
212
+ return None
213
+ mjs = getattr(model, "model_json_schema", None)
214
+ if callable(mjs):
215
+ try:
216
+ return mjs() # type: ignore[no-any-return]
217
+ except Exception:
218
+ pass
219
+ schema_fn = getattr(model, "schema", None)
220
+ if callable(schema_fn):
221
+ try:
222
+ return schema_fn() # type: ignore[no-any-return]
223
+ except Exception:
224
+ pass
225
+ ann = getattr(model, "__annotations__", None)
226
+ if isinstance(ann, dict):
227
+ return {"type": "object", "properties": {k: {"type": "string"} for k in ann.keys()}}
228
+ return None
229
+
230
+
231
+ def _extract_defs_from_schema(schema: Dict[str, Any], components_schemas: Dict[str, Any]) -> Dict[str, Any]:
232
+ """Extract $defs from a schema, add them to components_schemas, and rewrite $refs.
233
+
234
+ Pydantic's model_json_schema() generates JSON Schema 2020-12 style with $defs
235
+ for nested model references. OpenAPI 3.0 expects schemas under #/components/schemas/.
236
+ This function extracts $defs, moves them to components_schemas, and rewrites
237
+ $ref values from #/$defs/ModelName to #/components/schemas/ModelName.
238
+ """
239
+ if not isinstance(schema, dict):
240
+ return schema
241
+
242
+ # Make a copy to avoid mutating the original
243
+ schema = dict(schema)
244
+
245
+ # Extract $defs and add to components_schemas
246
+ if "$defs" in schema:
247
+ defs = schema.pop("$defs")
248
+ for name, definition in defs.items():
249
+ # Recursively process nested $defs in definitions
250
+ processed_def = _rewrite_refs(definition)
251
+ components_schemas[name] = processed_def
252
+
253
+ # Rewrite $refs in the schema
254
+ return _rewrite_refs(schema)
255
+
256
+
257
+ def _rewrite_refs(obj: Any) -> Any:
258
+ """Recursively rewrite $ref values from #/$defs/X to #/components/schemas/X."""
259
+ if isinstance(obj, dict):
260
+ result = {}
261
+ for key, value in obj.items():
262
+ if key == "$ref" and isinstance(value, str) and value.startswith("#/$defs/"):
263
+ # Rewrite the ref to point to components/schemas
264
+ model_name = value[len("#/$defs/"):]
265
+ result[key] = f"#/components/schemas/{model_name}"
266
+ else:
267
+ result[key] = _rewrite_refs(value)
268
+ return result
269
+ elif isinstance(obj, list):
270
+ return [_rewrite_refs(item) for item in obj]
271
+ else:
272
+ return obj
273
+
274
+
275
+ def _extract_named_groups(regex: str) -> List[str]:
276
+ pattern = re.compile(regex)
277
+ return list(pattern.groupindex.keys())
278
+
279
+ def _regex_to_openapi_path(regex: str) -> str:
280
+ try:
281
+ path = regex
282
+ if path.startswith("^"):
283
+ path = path[1:]
284
+ if path.endswith("$"):
285
+ path = path[:-1]
286
+ path = re.sub(r"\(\?P<([^>]+)>[^)]+\)", r"{\1}", path)
287
+ return path
288
+ except Exception:
289
+ return regex
@@ -0,0 +1,72 @@
1
+ Metadata-Version: 2.4
2
+ Name: datasette-plugin-router
3
+ Version: 0.0.1a2
4
+ Summary: WIP router for Datasette plugins
5
+ Author: Alex Garcia
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/datasette/datasette-plugin-router
8
+ Project-URL: Changelog, https://github.com/datasette/datasette-plugin-router/releases
9
+ Project-URL: Issues, https://github.com/datasette/datasette-plugin-router/issues
10
+ Project-URL: CI, https://github.com/datasette/datasette-plugin-router/actions
11
+ Classifier: Framework :: Datasette
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: datasette>=1a23
16
+ Requires-Dist: pydantic>=2.12.5
17
+ Requires-Dist: python-openapi>=0.2.0
18
+ Dynamic: license-file
19
+
20
+ # datasette-plugin-router
21
+
22
+ [![PyPI](https://img.shields.io/pypi/v/datasette-plugin-router.svg)](https://pypi.org/project/datasette-plugin-router/)
23
+ [![Changelog](https://img.shields.io/github/v/release/datasette/datasette-plugin-router?include_prereleases&label=changelog)](https://github.com/datasette/datasette-plugin-router/releases)
24
+ [![Tests](https://github.com/datasette/datasette-plugin-router/actions/workflows/test.yml/badge.svg)](https://github.com/datasette/datasette-plugin-router/actions/workflows/test.yml)
25
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/datasette/datasette-plugin-router/blob/main/LICENSE)
26
+
27
+ WIP router for Datasette plugins
28
+
29
+ Datasette plugins that have a lot of [custom API endpoints](https://docs.datasette.io/en/stable/plugin_hooks.html#register-routes-datasette) can get tiresome to write by hand. `datasette-plugin-router` aims to be a small Python library that adds a FastAPI-like API for defining custom Datasette plugin endpoints.
30
+
31
+ - Define routes with familiar GET/POST decorators
32
+ - Define Pydantic-backed input/output schemas on JSON endpoints
33
+ - `register_routes()` compatability
34
+ - export to OpenAPI schema for codegen'ing clients
35
+
36
+
37
+ Sample usage:
38
+
39
+ ```python
40
+ from datasette import Response, hookimpl
41
+ from datasette_plugin_router import Router, Body
42
+ from pydantic import BaseModel
43
+
44
+ router = Router()
45
+
46
+ class Input(BaseModel):
47
+ id: int
48
+ name: str
49
+
50
+ class Output(BaseModel):
51
+ id_negative: int
52
+ name_upper: str
53
+
54
+ @router.POST(r"/-/demo1$", output=Output)
55
+ async def demo1(params: Body[Input]) -> Output:
56
+ output = Output(
57
+ id_negative=-1 * params.id,
58
+ name_upper=params.name.upper(),
59
+ )
60
+ return Response.json(output.model_dump())
61
+
62
+
63
+ @router.GET(r"/-/hello/(?P<name>.*)$")
64
+ async def hello(name: str):
65
+ return Response.html(f"<h1>Hello, {name}!</h1>")
66
+
67
+
68
+ @hookimpl
69
+ def register_routes():
70
+ return router.routes()
71
+
72
+ ```
@@ -0,0 +1,8 @@
1
+ datasette_plugin_router/__init__.py,sha256=Hob8dbfwKJ8gOejDutdlC3wNPTlQJ4ECkQz_Q8b51PM,11687
2
+ datasette_plugin_router-0.0.1a2.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
3
+ tests/test_plugin_router.py,sha256=OoMEFsjPEmLK1aI5VL0MMBM-OGFPdI7QXuXeBp8h-UE,5747
4
+ datasette_plugin_router-0.0.1a2.dist-info/METADATA,sha256=Fpp_qVcz_d-LWaWm1R51Izz1I8HHGpfFU2oeHrxv9RQ,2656
5
+ datasette_plugin_router-0.0.1a2.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
6
+ datasette_plugin_router-0.0.1a2.dist-info/entry_points.txt,sha256=t3H60Uv6J7kUBQpJLGrtKtX0IG4a-qP92GHZ2OhYyxM,52
7
+ datasette_plugin_router-0.0.1a2.dist-info/top_level.txt,sha256=1yxh_A8rPbDc9d97jjp0B9QNTPxRyqpbC_v03vAm-vc,30
8
+ datasette_plugin_router-0.0.1a2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.10.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [datasette]
2
+ plugin_router = datasette_plugin_router
@@ -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 reasonable and customary use in describing the
141
+ origin of the Work and 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 [yyyy] [name of copyright owner]
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,2 @@
1
+ datasette_plugin_router
2
+ tests
@@ -0,0 +1,157 @@
1
+ from datasette.app import Datasette
2
+ import pytest
3
+ from datasette_plugin_router import Router, Body
4
+ from pydantic import BaseModel
5
+ from datasette import hookimpl, Response
6
+ from typing import List, Annotated
7
+
8
+ @pytest.mark.asyncio
9
+ async def test_plugin_is_installed():
10
+ datasette = Datasette(memory=True)
11
+ response = await datasette.client.get("/-/plugins.json")
12
+ assert response.status_code == 200
13
+ installed_plugins = {p["name"] for p in response.json()}
14
+ assert "datasette-plugin-router" in installed_plugins
15
+
16
+
17
+
18
+ @pytest.mark.asyncio
19
+ async def test_spec(snapshot):
20
+ datasette = Datasette(memory=True)
21
+ class Input(BaseModel):
22
+ id: int
23
+
24
+ class Output(BaseModel):
25
+ id_negative: int
26
+
27
+ router = Router(title="Test API", version="1.2.3", server_url="http://example.com")
28
+
29
+ @router.POST("/test", output=Output)
30
+ async def test_endpoint(params: Annotated[Input, Body()]):
31
+ return Response.json(Output(id_negative=-1 * params.id).model_dump())
32
+
33
+ @router.GET(r"/hello/(?P<name>.*)$")
34
+ async def hello(name: str):
35
+ return Response.html(f"<h1>Hello, {name}!</h1>")
36
+
37
+ assert router.openapi_document_json() == snapshot(name="router spec")
38
+
39
+ class TestPlugin:
40
+ __name__ = "TestPlugin"
41
+
42
+ @hookimpl
43
+ def register_routes(datasette):
44
+ return router.routes()
45
+
46
+ try:
47
+ datasette.pm.register(TestPlugin(), name="test-plugin")
48
+
49
+ result = await datasette.client.post("/test", json={"id": 42})
50
+ assert result.status_code == 200
51
+ assert result.json() == {"id_negative": -42}
52
+
53
+ finally:
54
+ datasette.pm.unregister(name="test-plugin")
55
+
56
+
57
+ @pytest.mark.asyncio
58
+ async def test_nested_pydantic_models_openapi():
59
+ """Test that nested Pydantic models generate valid OpenAPI with components.schemas."""
60
+
61
+ class DocumentListItem(BaseModel):
62
+ id: int
63
+ title: str
64
+
65
+ class DocumentListOutput(BaseModel):
66
+ documents: List[DocumentListItem]
67
+ total: int
68
+
69
+ router = Router(title="Nested API", version="1.0.0", server_url="http://example.com")
70
+
71
+ @router.GET("/documents", output=DocumentListOutput)
72
+ async def list_documents():
73
+ return Response.json({"documents": [], "total": 0})
74
+
75
+ spec = router.openapi_document_json()
76
+
77
+ # Verify that $defs was extracted and moved to components.schemas
78
+ assert "components" in spec, "Should have components section"
79
+ assert "schemas" in spec["components"], "Should have schemas in components"
80
+ assert "DocumentListItem" in spec["components"]["schemas"], "Should have DocumentListItem in schemas"
81
+
82
+ # Verify the nested model schema is correct
83
+ item_schema = spec["components"]["schemas"]["DocumentListItem"]
84
+ assert item_schema["type"] == "object"
85
+ assert "id" in item_schema["properties"]
86
+ assert "title" in item_schema["properties"]
87
+
88
+ # Verify the response schema uses the correct $ref
89
+ response_schema = spec["paths"]["/documents"]["get"]["responses"]["200"]["content"]["application/json"]["schema"]
90
+ assert "$defs" not in response_schema, "Should not have $defs in inline schema"
91
+
92
+ # Verify the $ref points to components/schemas
93
+ docs_property = response_schema["properties"]["documents"]
94
+ assert docs_property["items"]["$ref"] == "#/components/schemas/DocumentListItem"
95
+
96
+
97
+ @pytest.mark.asyncio
98
+ async def test_annotated_body_syntax():
99
+ """Test that Annotated[Model, Body()] syntax works for type-safe parameters."""
100
+ datasette = Datasette(memory=True)
101
+
102
+ class Input(BaseModel):
103
+ id: int
104
+ name: str
105
+
106
+ class Output(BaseModel):
107
+ id_negative: int
108
+ name_upper: str
109
+
110
+ router = Router(title="Annotated API", version="1.0.0", server_url="http://example.com")
111
+
112
+ # Using Annotated[Model, Body()] for full type safety
113
+ @router.POST("/annotated-test", output=Output)
114
+ async def test_endpoint(params: Annotated[Input, Body()]):
115
+ # params is now properly typed as Input, not Body[Input]
116
+ # Type checkers understand params.id is int, params.name is str
117
+ return Response.json(Output(
118
+ id_negative=-1 * params.id,
119
+ name_upper=params.name.upper()
120
+ ).model_dump())
121
+
122
+ class TestPlugin:
123
+ __name__ = "AnnotatedTestPlugin"
124
+
125
+ @hookimpl
126
+ def register_routes(datasette):
127
+ return router.routes()
128
+
129
+ try:
130
+ datasette.pm.register(TestPlugin(), name="annotated-test-plugin")
131
+
132
+ # Test the endpoint works correctly
133
+ result = await datasette.client.post("/annotated-test", json={"id": 42, "name": "hello"})
134
+ assert result.status_code == 200
135
+ assert result.json() == {"id_negative": -42, "name_upper": "HELLO"}
136
+
137
+ # Verify OpenAPI spec is generated correctly
138
+ spec = router.openapi_document_json()
139
+ assert "/annotated-test" in spec["paths"]
140
+ post_spec = spec["paths"]["/annotated-test"]["post"]
141
+
142
+ # Should have request body schema
143
+ assert "requestBody" in post_spec
144
+ assert post_spec["requestBody"]["required"] is True
145
+ request_schema = post_spec["requestBody"]["content"]["application/json"]["schema"]
146
+ assert "properties" in request_schema
147
+ assert "id" in request_schema["properties"]
148
+ assert "name" in request_schema["properties"]
149
+
150
+ # Should have response schema
151
+ response_schema = post_spec["responses"]["200"]["content"]["application/json"]["schema"]
152
+ assert "properties" in response_schema
153
+ assert "id_negative" in response_schema["properties"]
154
+ assert "name_upper" in response_schema["properties"]
155
+
156
+ finally:
157
+ datasette.pm.unregister(name="annotated-test-plugin")