Swagger UI Bundle
Swagger UI bundle provides the static files for Swagger UI, making it easy to integrate into Python web frameworks without needing to manage frontend assets. It ships a specific version of Swagger UI, which is then served by the user's web application. The current version is 1.1.0. Release cadence is infrequent, typically aligning with significant upstream Swagger UI updates or maintenance.
Warnings
- breaking Version 1.1.0 includes a major update to the bundled Swagger UI (from 3.x to 4.x). While the Python API `swagger_ui_path` remains stable, any custom JavaScript or CSS directly interacting with or relying on specific internal structures of the Swagger UI frontend might break.
- gotcha This library only provides the filesystem path to the Swagger UI assets. It does not include a built-in web server or a direct integration with any specific web framework. You must explicitly configure your web framework (e.g., Flask, Django, FastAPI) to serve these static files.
- gotcha The version of Swagger UI bundled with this library may not always be the absolute latest upstream version. `swagger-ui-bundle` updates its bundled Swagger UI only when a new version of the Python package is released.
Install
-
pip install swagger-ui-bundle Flask Jinja2
Imports
- swagger_ui_path
from swagger_ui_bundle import swagger_ui_path
Quickstart
import os
from flask import Flask, render_template_string, send_from_directory
from swagger_ui_bundle import swagger_ui_path
app = Flask(__name__)
# 1. Route to serve Swagger UI static files
@app.route('/swagger-ui-assets/<path:filename>')
def serve_swagger_ui_assets(filename):
return send_from_directory(swagger_ui_path, filename)
# 2. Route to serve your OpenAPI specification (example)
@app.route('/openapi.json')
def serve_openapi_spec():
return {
"openapi": "3.0.0",
"info": {"title": "Sample API", "version": "1.0.0"},
"paths": {
"/hello": {
"get": {
"summary": "Says hello",
"responses": {"200": {"description": "A greeting"}}
}
}
}
}
# 3. Route to display the Swagger UI page
@app.route('/docs/')
def show_swagger_ui():
html_content = '''
<!DOCTYPE html>
<html>
<head>
<title>Swagger UI</title>
<link rel="stylesheet" type="text/css" href="/swagger-ui-assets/swagger-ui.css">
</head>
<body>
<div id="swagger-ui"></div>
<script src="/swagger-ui-assets/swagger-ui-bundle.js"></script>
<script src="/swagger-ui-assets/swagger-ui-standalone-preset.js"></script>
<script>
window.onload = function() {
SwaggerUIBundle({
url: "/openapi.json", // URL to your OpenAPI spec
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
layout: "StandaloneLayout"
});
};
</script>
</body>
</html>
'''
return render_template_string(html_content)
if __name__ == '__main__':
# Run this example after installing Flask: pip install Flask
print(f"Swagger UI bundle path: {swagger_ui_path}")
print("Go to http://127.0.0.1:5000/docs/ to see the Swagger UI.")
app.run(debug=True)