Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for SwaggerUI #302

Merged
merged 2 commits into from
Jul 22, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions starlite/openapi/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,60 @@ def retrieve_schema_json(self, request: Request) -> "OpenAPI":
"""Returns the openapi schema"""
return self.schema_from_request(request)

@get(path="/swagger", media_type=MediaType.HTML, include_in_schema=False)
def swagger_ui(self, request: Request) -> str:
"""Endpoint that serves SwaggerUI"""
schema = self.schema_from_request(request)
if self.dumped_schema == "":
# Note: Fix for Swagger rejection OpenAPI >=3.1
# We force the version to be lower to get the default JS bundle to accept it
# This works flawlessly as the main blocker for Swagger support for OpenAPI 3.1 is JSON schema support
# Since we use the YAML format this is not an issue for us and we can do this trick to get support right now
# We use deepcopy to avoid changing the actual schema on the request. Since this is a cached call the effect is minimal
schema_copy = schema.copy()
schema_copy.openapi = "3.0.3"
self.dumped_schema = dumps(schema_copy.json(by_alias=True, exclude_none=True), option=OPT_INDENT_2).decode(
"utf-8"
)
head = f"""
<head>
<title>{schema.info.title}</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@4/swagger-ui.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@4/swagger-ui-bundle.js"></script>
<style>
{self.styles}
</style>
</head>
"""
body = f"""
<body>
<div id='swagger-container'></div>
<script>
const ui = SwaggerUIBundle({{
spec: JSON.parse({self.dumped_schema}),
dom_id: '#swagger-container',
layout: 'BaseLayout',
deepLinking: true,
showExtensions: true,
showCommonExtensions: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset
],
}})
</script>
</body>
"""
return f"""
<!DOCTYPE html>
<html>
{head}
{body}
</html>
"""

@get(media_type=MediaType.HTML, include_in_schema=False)
def redoc(self, request: Request) -> str: # pragma: no cover
"""Endpoint that serves Redoc"""
Expand Down