DEV Community

Lívia Silva Santos
Lívia Silva Santos

Posted on

Disabling Swagger' button *try it out*

We all know how important is to document and expose your services.

Swagger (https://swagger.io/) makes it easy to configure a way to expose your services and permit the user to execute them.

But sometimes, we do not want to enable the Try it Out button, for security reasons, for example.

I've found out 2 workarounds (not sure they're the best solutions to everycase, though):

1 - Change the host parameter, so Swagger will execute the service not in the same host of the service:

Swagger swagger = new Reader(new Swagger()).read(getClasses());
if (envProduction) {
  swagger.setHost("host.i.want.the.services.to.be.executed");
}

So, if my 'service' is being hosted in 'http://host.com/context/api/service', when Swagger' button 'Try it out' is pressed, it will call 'http://host.i.want.the.services.to.be.executed/context/api/service'.

2 - Add a plugin via Javascript do disabled the button, edit index.html where SwaggerUIBundle is created:

<script>
  window.onload = function() {
    const DisableTryItOutPlugin = function() {
      return {
        statePlugins: {
          spec: {
            wrapSelectors: {
              allowTryItOutFor: () => () => false
            }
           }
         }
       }
     }

     const ui = SwaggerUIBundle({
       url: window.location.protocol + "//" + window.location.host + "/boletos/servicos/documentacao",
       dom_id: '#swagger-ui',
       deepLinking: true,
       validatorUrl: null,
       presets: [
         SwaggerUIBundle.presets.apis,
         SwaggerUIStandalonePreset
       ],
       plugins: [
         SwaggerUIBundle.plugins.DownloadUrl,
         DisableTryItOutPlugin
       ],
       layout: "StandaloneLayout"
     })

     window.ui = ui
   }
</script>

Do you know a better way do disable that button? Let me know in the comments! I'd love to learn more!

Thanks!

Top comments (0)