python-restx / flask-restx

Fork of Flask-RESTPlus: Fully featured framework for fast, easy and documented API development with Flask
https://flask-restx.readthedocs.io/en/latest/
Other
2.16k stars 335 forks source link

How to correctly use `swagger-config.yaml`? #430

Closed hubodz closed 2 years ago

hubodz commented 2 years ago

Could you please advice what should be exact location of the swagger-config.yaml file?

The doc says "the project root directory" (which I understood the root of my Flask/Restx code). Unfortunately, after placing it there and starting an application, there is no result.

Just for clarity, here is how my swagger-config.yaml looks like:

---
syntaxHighlight: false
peter-doggart commented 2 years ago

@hubodz I couldn't get swagger-config.yaml to work out-of-the-box putting it anywhere in my project, but you can render a custom template and define your configuration as part of the call to SwaggerUIBundle.

You can copy the flask-restx default swagger templates into your project from https://github.com/python-restx/flask-restx/tree/master/flask_restx/templates

I use blueprints in my project, so I moved them into a folder inside one of the Blueprints like:

- application
    - api_1 (blueprint)
        - templates
            - swagger-ui-css.html
            - swagger-ui-custom.html
            - swagger-ui-libs.html

Then it's just a case of telling the Blueprint the location of the templates folder and defining an `Api:

api_bp = Blueprint("api_1", __name__, url_prefix="/api_1/v1", template_folder="templates")

api = Api(
    api_bp,
    version="1.0",
    title=TITLE,
    description=DESCRIPTION,
    doc="/doc",
    validate=True,
)

Then you can use the @api.documentation decorate to over-ride the default swagger behaviour.

@api.documentation
def custom_ui():
    return render_template(
        "swagger-ui-custom.html", title=api.title, specs_url=api.specs_url
    )

My swagger-ui-custom.html is just a copy of the default one with the configurations I want set. In this case defaultModelsExpandDepth: -1 so the models view is hidden:

<script type="text/javascript">
        window.onload = function() {
            const ui = window.ui = new SwaggerUIBundle({
                url: "{{ specs_url }}",
                defaultModelsExpandDepth: -1,
               ....

I haven't tested this in production but it appears to work fine on my local server.

hubodz commented 2 years ago

Hello @peter-doggart That's a smart solution! Thanks!