-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-schema.py
More file actions
71 lines (57 loc) · 2.1 KB
/
generate-schema.py
File metadata and controls
71 lines (57 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"""Script to generate an OpenAPI schema."""
import argparse
import json
from pathlib import Path
from typing import Any
import jinja2
from pydantic import BaseModel
from structured_tutorials.models.tutorial import TutorialModel
parser = argparse.ArgumentParser()
parser.add_argument("--swagger-path", type=Path, default=Path.cwd() / "docs" / "_static" / "swagger-ui")
parser.add_argument(
"-o", "--output", action="store_true", default=False, help="Write schema to stdout as well."
)
args = parser.parse_args()
swagger_initializer = """window.onload = function() {
//<editor-fold desc="Changeable Configuration Block">
// the following lines will be replaced by docker/configurator, when it runs in a docker-container
window.ui = SwaggerUIBundle({
spec: {{ spec }},
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
});
//</editor-fold>
}"""
def generate_openapi_schema(
model: type[BaseModel], title: str = "Structured Tutorials model reference", version: str = "1.0.0"
) -> dict[str, Any]:
"""Generate the OpenAPI schema for the given model."""
# Generate Pydantic v2 JSON schema
schema = model.model_json_schema(ref_template="#/components/schemas/{model}")
schemas = schema.get("$defs", {}).copy()
schemas[model.__name__] = schema
# Minimal OpenAPI 3.0.0 document with only components
openapi = {
"openapi": "3.0.0",
"info": {"title": title, "version": version},
"paths": {}, # no API paths
"components": {"schemas": schemas},
}
return openapi
openapi = generate_openapi_schema(TutorialModel)
env = jinja2.Environment()
template = env.from_string(swagger_initializer)
swagger_js = template.render(spec=json.dumps(openapi, indent=4, sort_keys=True))
with open(args.swagger_path / "swagger-initializer.js", "w") as fh:
fh.write(swagger_js)
if args.output:
schema = TutorialModel.model_json_schema()
print(json.dumps(schema, indent=4, sort_keys=True))