swaggeropenapiswagger-2.0

Swagger with basepath on the same host as swagger definition


I've read upon the basePath spec of swagger from here. However, it seems that my current scenario is not among the ones listed here.

I need to basically:

Scenario is:

Reason is that the API is hosted on the same domain, so the API call will just work when they hit "Try it out" as long as a basePath is selected (or it defaults to the latest one, e.g. "v2").

Any idea on how the "servers" property would look like in such a scenario?

I've tried multiple times and I can't seem to work it out.

I am using the YAML format, so no code-builders or anything.


Solution

  • In OpenAPI 3.x, servers[].url can be relative, in which case it's resolved against the location of the OpenAPI file (not the location of the docs page that renders the OpenAPI file).

    You can use:

    openapi: 3.1.1
    
    servers:
      - url: /v1
      - url: /v2
    
    paths:
      /something:
        ...
    

    Assuming the OpenAPI file lives at

    https://their_company_subdomain.myapp.com/path/to/openapi.yaml
    

    the API server paths resolve to

    https://their_company_subdomain.myapp.com/v1
    https://their_company_subdomain.myapp.com/v2
    

    and the endpoint path resolves to

    https://their_company_subdomain.myapp.com/v1/something
    https://their_company_subdomain.myapp.com/v2/something
    

    OpenAPI renderers that support multiple servers will display a dropdown for users to select the target server. For example, here's how it looks in Swagger UI:

    Server selector in Swagger UI

    Server selector in Swagger UI