-
Notifications
You must be signed in to change notification settings - Fork 0
/
offline_openapi.py
90 lines (69 loc) · 2.52 KB
/
offline_openapi.py
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
from time import perf_counter
from wsgiref.simple_server import make_server
import falcon
import msgspec
from falcon import App, Request, Response
from offapi import OpenAPITemplate
from defspec import OpenAPI
class JSONRequest(msgspec.Struct, frozen=True):
title: str
timeout: float
class Query(msgspec.Struct, frozen=True):
limit: int
offset: int
class JSONResponse(msgspec.Struct, frozen=True):
elapsed: float
queries: list[Query]
class FakeResource:
def on_post(self, req: Request, resp: Response):
start = perf_counter()
request: JSONRequest = msgspec.json.decode(
req.bounded_stream.read(), type=JSONRequest, strict=False
)
print(request)
query: Query = msgspec.convert(req.params, Query, strict=False)
response = JSONResponse(elapsed=perf_counter() - start, queries=[query])
resp.data = msgspec.json.encode(response)
class HealthCheck:
def on_get(self, req: Request, resp: Response):
resp.text = "OK"
resp.content_type = falcon.MEDIA_TEXT
class OpenAPIResource:
def __init__(self) -> None:
self.openapi = OpenAPI()
self.openapi.register_route("/", "get", summary="health check")
self.openapi.register_route(
"/fake",
"post",
summary="fake endpoint",
request_type=JSONRequest,
response_type=JSONResponse,
query_type=Query,
)
self.spec = self.openapi.to_json()
def on_get(self, req: Request, resp: Response):
resp.content_type = falcon.MEDIA_JSON
resp.data = self.spec
class OpenAPIRender:
def __init__(self, spec_url: str, template: OpenAPITemplate) -> None:
self.template = template.value.format(spec_url=spec_url)
def on_get(self, req: Request, resp: Response):
resp.content_type = falcon.MEDIA_HTML
resp.text = self.template
if __name__ == "__main__":
app = App()
app.add_route("/", HealthCheck())
app.add_route("/fake", FakeResource())
app.add_route("/openapi/spec.json", OpenAPIResource())
app.add_route(
"/openapi/redoc", OpenAPIRender("/openapi/spec.json", OpenAPITemplate.REDOC)
)
app.add_route(
"/openapi/swagger", OpenAPIRender("/openapi/spec.json", OpenAPITemplate.SWAGGER)
)
app.add_route(
"/openapi/scalar", OpenAPIRender("/openapi/spec.json", OpenAPITemplate.SCALAR)
)
with make_server("", 8000, app) as server:
print("Serving on port 8000...")
server.serve_forever()