-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflask_openapi.py
76 lines (52 loc) · 1.56 KB
/
flask_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
from dataclasses import asdict, dataclass
from time import perf_counter
from flask import Flask, request
from defspec import OpenAPI, RenderTemplate
@dataclass
class JSONRequest:
title: str
timeout: float
@dataclass
class Query:
limit: int
offset: int
@dataclass
class JSONResponse:
elapsed: float
queries: list[Query]
app = Flask(__name__)
@app.route("/fake", methods=["POST"])
def fake():
start = perf_counter()
req: JSONRequest = JSONRequest(**request.json)
print(req)
query: Query = Query(**request.args)
response = JSONResponse(elapsed=perf_counter() - start, queries=[query])
return asdict(response)
@app.route("/", methods=["GET"])
def health_check():
return "OK"
@app.route("/openapi/spec.json", methods=["GET"])
def spec():
openapi = OpenAPI()
openapi.register_route("/", "get", summary="health check")
openapi.register_route(
"/fake",
"post",
summary="fake endpoint",
request_type=JSONRequest,
response_type=JSONResponse,
query_type=Query,
)
return openapi.to_dict()
@app.route("/openapi/redoc", methods=["GET"])
def redoc():
return RenderTemplate.REDOC.value.format(spec_url="/openapi/spec.json")
@app.route("/openapi/swagger", methods=["GET"])
def swagger():
return RenderTemplate.SWAGGER.value.format(spec_url="/openapi/spec.json")
@app.route("/openapi/scalar", methods=["GET"])
def scalar():
return RenderTemplate.SCALAR.value.format(spec_url="/openapi/spec.json")
if __name__ == "__main__":
app.run(debug=True, port=8000)