Swagger UI Bundle

1.1.0 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to use `swagger_ui_path` with Flask to serve the Swagger UI assets and display an API documentation page. The core idea is to expose the directory returned by `swagger_ui_path` via your web framework's static file serving mechanism and then reference these files in an HTML template.

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)

view raw JSON →