Skip to content

Add support for adding decorators to the OpenAPI spec and documentation UI endpoints #483

@tsokalski

Description

@tsokalski

As a user of the APIFlask framework, I would like the ability to apply a decorator to the endpoints used to serve the OpenAPI spec as well as the documentation UI, so that I can execute additional logic before returning back the OpenAPI spec or the documentation UI to a client.

The more specific use case I have for this is to apply some security checks to validate that the client trying to access the documentation is allowed to access the endpoints that serve it.

I have currently achieved this by doing the following, but it's rather ugly - I had to look into the code in APIFlask._register_openapi_blueprint and replicate some of its logic to rewrite the view functions, which Flask advises against doing:

def _add_authentication_to_docs(app: APIFlask) -> None:
    if app.spec_path:
        _rewrite_view_function(app, "spec")
    if app.docs_path:
        _rewrite_view_function(app, "docs")
        if app.docs_ui == "swagger-ui" and app.docs_oauth2_redirect_path:
            _rewrite_view_function(app, "swagger_ui_oauth_redirect")


def _rewrite_view_function(app: APIFlask, method_name: str) -> None:
    # Flask warns you not to do this, but we don't really have a choice...
    app.view_functions[f"openapi.{method_name}"] = authenticate_apidocs()(app.view_functions[f"openapi.{method_name}"])

APIFairy provides this functionality via the APIFAIRY_APISPEC_DECORATORS and APIFAIRY_UI_DECORATORS config variables, which is much more straightforward:

app.config["APIFAIRY_APISPEC_DECORATORS"] = [authenticate_apidocs()]
app.config["APIFAIRY_UI_DECORATORS"] = [authenticate_apidocs()]

I am hoping that this framework might consider adopting similar functionality.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions