Skip to content

Setting server variable using js #10238

Open
@siemandalorian

Description

@siemandalorian

Q&A (please complete the following information)

  • OS: macOS
  • Method of installation: dist
  • Swagger-UI version: 5.18.2

Content & configuration

Swagger/OpenAPI definition:

openapi: 3.0.2
info:
  description: |
    My API
servers:
  - url: https://my-url.com/{my-server-variable}
    variables:
      my-server-variable:
        default: default-value

Swagger-UI configuration options:

document.querySelectorAll(".openapi"), item => {
          const ui = SwaggerUIBundle({
                url: item.getAttribute("data-openapi-url"),
                domNode: item,
                plugins: [SwaggerUIBundle.plugins.DownloadUrl],
                requestInterceptor: (request) => {
                  var inputField = document.getElementById("auth-bearer-value");
                  var inputValue = inputField.value;
                  request.headers['authorization'] = 'Bearer ' + inputValue;
                  return request;
                },
              })

How can we help?

Problem:
I have multiple openAPI specs rendered on single page using swagger-ui. I don't want to authorize and write server variables to each of the API separately but do it once and use in all APIs. I was able to do the authorization part by using requestInterceptor and inserting the token based on the input inserted by the user but I struggle with server variables.

Is there a way to set a server variable using javascript based on user input coming from a field ?
Currently after the user sets the value in general field I set the value programatically in each server variable inputs coming from swagger-ui and trigger the change event on them but the computedUrl is not changing. Also when I click on any endpoint at the API the default value appears back again.

Code how setting the value looks like:

document.getElementById("my_input").addEventListener("input", function () {
        const newValue = this.value;
        document.querySelectorAll('input[data-variable="my-server-variable"]').forEach(input => {
          input.value = newValue;
          input.setAttribute("value", newValue);
          const changeEvent = new Event('change', {
                    bubbles: true,
                    cancelable: true
                });
          input.dispatchEvent(changeEvent);
        });
      })

I would appreciate any hints how to achieve that.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions