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

Improve on the Swagger doc #512

Merged
merged 2 commits into from
Jan 25, 2024
Merged
Show file tree
Hide file tree
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
13 changes: 9 additions & 4 deletions asab/api/doc.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def __init__(self, api_service, app, web_container, config_section_name="asab:do
self.ServerUrls: str = asab.Config.get(config_section_name, "server_urls", fallback="/").strip().split("\n")


def build_swagger_documentation(self) -> dict:
def build_swagger_documentation(self, host) -> dict:
"""
Take a docstring of the class and a docstring of methods and merge them into Swagger data.
"""
Expand All @@ -65,7 +65,7 @@ def build_swagger_documentation(self) -> dict:
"version": "1.0.0",
},
"servers": [
{"url": url} for url in self.ServerUrls
{"url": "http://{}".format(host)}
],

# Base path relative to openapi endpoint
Expand Down Expand Up @@ -261,11 +261,13 @@ async def doc(self, request):
swagger_js_url: str = "https://unpkg.com/swagger-ui-dist@4/swagger-ui-bundle.js"
swagger_css_url: str = "https://unpkg.com/swagger-ui-dist@4/swagger-ui.css"

base_url = request.headers.get('Host')

doc_page = SWAGGER_DOC_PAGE.format(
title=self.App.__class__.__name__,
swagger_css_url=swagger_css_url,
swagger_js_url=swagger_js_url,
openapi_url="./asab/v1/openapi",
openapi_url="http://{}/asab/v1/openapi".format(base_url),
)

return aiohttp.web.Response(text=doc_page, content_type="text/html")
Expand Down Expand Up @@ -293,8 +295,11 @@ async def openapi(self, request):
url: https://swagger.io/specification/

"""

host = request.headers.get('Host')

return aiohttp.web.Response(
text=(yaml.dump(self.build_swagger_documentation(), sort_keys=False)),
text=(yaml.dump(self.build_swagger_documentation(host=host), sort_keys=False)),
content_type="text/yaml",
)

Expand Down
47 changes: 19 additions & 28 deletions asab/api/doc_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,31 +79,22 @@
</html>"""

SWAGGER_DOC_PAGE = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link type="text/css" rel="stylesheet" href="{swagger_css_url}">
<title>{title} API Documentation</title>
<style>
code {{ tab-size: 4; }}
pre {{ tab-size: 4; }}
</style>
</head>
<body>
<div id="swagger-ui"></div>
<script src="{swagger_js_url}"></script>
<script>
window.onload = () => {{
window.ui = SwaggerUIBundle({{
url: '{openapi_url}',
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset
]
}})
}}
</script>
</body>
</html>"""
<html>
<head>
<title>API Reference {openapi_url}</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {{
margin: 0;
}}
</style>
</head>
<body>
<script
id="api-reference"
data-url="{openapi_url}"></script>
<script src="https://www.unpkg.com/@scalar/api-reference"></script>
</body>
</html>
"""
9 changes: 8 additions & 1 deletion asab/web/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def __init__(self, app):
self.service = WebService(app, "asab.WebService")


def create_web_server(app, section: str = "web", config: typing.Optional[dict] = None) -> aiohttp.web.UrlDispatcher:
def create_web_server(app, section: str = "web", config: typing.Optional[dict] = None, api: bool = False) -> aiohttp.web.UrlDispatcher:
"""
Build the web server with the specified configuration.

Expand Down Expand Up @@ -49,6 +49,13 @@ async def hello(self, request):
app.add_module(Module)
websvc = app.get_service("asab.WebService")
container = WebContainer(websvc, section, config=config)

if api:
# The DiscoverySession is functional only with ApiService initialized.
from ..api import ApiService
apisvc = ApiService(app)
apisvc.initialize_web(container)

return container.WebApp.router


Expand Down
4 changes: 3 additions & 1 deletion examples/webserver.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
#!/usr/bin/env python3

import asab.api
import asab.web.rest


Expand All @@ -14,7 +16,7 @@ def __init__(self):
super().__init__()

# Create the Web server
web = asab.web.create_web_server(self)
web = asab.web.create_web_server(self, api = True)

# Add a route to the handler method
web.add_get('/hello', self.hello)
Expand Down
Loading