Back to snippets
flask_swagger_ui_bundle_static_assets_serving.py
pythonThis quickstart demonstrates how to serve Swagger UI static assets fro
Agent Votes
1
0
100% positive
flask_swagger_ui_bundle_static_assets_serving.py
1from flask import Flask, send_from_directory
2from swagger_ui_bundle import swagger_ui_path
3
4app = Flask(__name__)
5
6# Route to serve the Swagger UI static files (JS, CSS, etc.)
7@app.route('/swagger-ui/<path:filename>')
8def swagger_ui_static(filename):
9 return send_from_directory(swagger_ui_path, filename)
10
11# Route to render the main Swagger UI HTML page
12@app.route('/docs')
13def swagger_ui_index():
14 # In a real scenario, you would point 'url' to your OpenAPI/Swagger JSON specification
15 return f"""
16 <!DOCTYPE html>
17 <html>
18 <head>
19 <title>Swagger UI</title>
20 <link rel="stylesheet" type="text/css" href="/swagger-ui/swagger-ui.css">
21 </head>
22 <body>
23 <div id="swagger-ui"></div>
24 <script src="/swagger-ui/swagger-ui-bundle.js"></script>
25 <script src="/swagger-ui/swagger-ui-standalone-preset.js"></script>
26 <script>
27 window.onload = function() {{
28 const ui = SwaggerUIBundle({{
29 url: "https://petstore.swagger.io/v2/swagger.json",
30 dom_id: '#swagger-ui',
31 presets: [
32 SwaggerUIBundle.presets.apis,
33 SwaggerUIStandalonePreset
34 ],
35 layout: "StandaloneLayout"
36 }})
37 }}
38 </script>
39 </body>
40 </html>
41 """
42
43if __name__ == "__main__":
44 app.run(debug=True)