Search code examples
flaskswaggerflask-restful

Changing root path of swagger bundle javascript


I'm having trouble in configuring the Swagger to my flask application which is deployed as a micro-service under another parent project.

As in the picture, the static files for Swagger are loaded like this <script src="/swaggerui/swagger-ui-bundle.js"></script>

This is causing problem since the .js is attempted to resolve from the root path which is parent application that I don't control.

Where to specify Swagger to look for a custom path while loading those Javascript ? Simply adding a dot . in front should solve the issue

My code is like this

from flask import Flask, Blueprint
from flask_restplus import Api

app = Flask(__name__)
blueprint = Blueprint('api', __name__, url_prefix='/api')
api = Api(blueprint, doc='/doc/')
app.register_blueprint(blueprint)

enter image description here


Solution

  • It was made possible by overriding swagger_static of the default template and passing necessary path via spec_url we can potentially change the path where swagger goes to look for the html & json.

    The complete solution is as below

    @apidoc.apidoc.add_app_template_global
    def swagger_static(filename):
        return "./swaggerui/{0}".format(filename)
    
    api = Api(app)
    
    @api.documentation
    def custom_ui():
        return render_template("swagger-ui.html", title=api.title, specs_url="./swagger.json")
    

    Linking Github discussion https://github.com/noirbizarre/flask-restplus/issues/262#issuecomment-542490899