What is the difference between SwaggerUIBundle, and SwaggerUi - swagger-ui

I've seen both in samples I've found and haven't seen how they are different. Is the bundle needed if you are using this in an HTML page only (not using a single-page-app) or is that the one to use if you are using a single-page-app?
The Swagger UI docs discuss two ways to deploy swagger-ui.
traditional npm - swagger-ui
dependency-free module - swagger-ui-dist
I've seen examples like this one where SwaggerUIBundle is used on what appears to be a web page hosted in tomcat (python, or some other web server) example.
<script src="./swagger-ui-bundle.js"> </script>
// later
<script>
window.onload = function() {
// Build a system
const ui = SwaggerUIBundle({
url: "https://petstore.swagger.io/v2/swagger.json",
But also seen examples like this one that use SwaggerUi.
window.swaggerUi = new SwaggerUi({
url: "http://petstore.swagger.wordnik.com/api/api-docs",
dom_id: "swagger-ui-container",
A search returns things like:
swagger-ui-bundle.js - https://github.com/swagger-api/swagger-ui/issues/3978
SwaggerUi - https://stackoverflow.com/a/29497301/3281336
SwaggerUIBundle - https://github.com/swagger-api/swagger-ui/wiki/FAQ

This page Installation Distribution Channels NPM Registry says:
SwaggerUIBundle is equivalent to SwaggerUI.
But then explains the differences. So they are functionally equivalent but the one you choose will depend on how your webserver/website is serving up the swagger user interface page.
The first example with const ui = SwaggerUIBundle(... is for Swagger UI 3.x, which is the current version of Swagger UI. The second example with window.swaggerUi = new SwaggerUi(... is for the old Swagger UI 2.x. Credit #Helen for this info in this answer)
For more details read on...
SwaggerUI Explained
SwaggerUI is used in apps that can import npm modules. This includes React, Angular or other single-page-apps (SPAs) that include the webpack-like tooling to package the resources for delivery to the browser.
The webpage says this:
import SwaggerUI from 'swagger-ui'
swagger-ui is meant for consumption by JavaScript web projects that include module bundlers, such as Webpack, Browserify, and Rollup.
Here's an example of using the npm intalled module swagger-ui.
import SwaggerUI from 'swagger-ui'
// or use require, if you prefer
const SwaggerUI = require('swagger-ui')
SwaggerUI({
dom_id: '#myDomId'
})
SwaggerUIBundle Explained
SwaggerUIBundle is used when your app does not support importing npm modules (e.g., a java webapp).
The swagger user interface can be loaded by using the swagger index.html page (included in the swagger-ui-bundle) or by your own personal html page that includes the bundle file and uses the Javascript shown below:
The following comes from the website and is edited to highlight my above statements:
The [...] dist folder [has] swagger-ui-bundle.js, which is a build of Swagger-UI that includes all the code it needs to run in one file. The folder also has an index.html asset, to make it easy to serve Swagger-UI...
An example of how to use the SwaggerUIBundle is:
var SwaggerUIBundle = require('swagger-ui-dist').SwaggerUIBundle
const ui = SwaggerUIBundle({
url: "https://petstore.swagger.io/v2/swagger.json",
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset
],
layout: "StandaloneLayout"
})
The SwaggerUIBundle example is confusing
It is confusing because it says:
if you're in a JavaScript project that can't handle a traditional npm module, you could do something like this:
var SwaggerUIBundle = require('swagger-ui-dist').SwaggerUIBundle
which uses require() which is an npm module way of including the bundle.
A less confusing way to explain this would be to say:
If you are using Swagger in a non-module environment then you need to somehow get the swagger bundle javascript loaded into the browser page and then use the SwaggerUIBundle as shown below to make the swagger user interface render at the dom_id specified (in the example below it is swagger-ui).
const ui = SwaggerUIBundle({
url: "https://petstore.swagger.io/v2/swagger.json",
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset
],
layout: "StandaloneLayout"
})
The way you load the swagger-ui-bundle onto your page will depend on the technologies you are using. If you want you can load the page using a <script src="bundle.js"></script>. See https://github.com/swagger-api/swagger-ui/blob/master/dist/index.html (which is in swagger-ui/dist/index.html).
If you are in a NodeJS express application you could load the swagger bundle onto the page using:
var SwaggerUIBundle = require('swagger-ui-dist').SwaggerUIBundle
How you get the swagger bundle javscript onto the page is up to you.

The first example with const ui = SwaggerUIBundle(... is for Swagger UI 3.x, which is the current version of Swagger UI.
The second example with window.swaggerUi = new SwaggerUi(... is for the old Swagger UI 2.x.
See here for the differences between 3.x and 2.x.

Related

Using rails asset in javascript

I'm using rails to build a site, and I want to embed a swagger doc in one of the pages. The swagger yaml file is stored in /app/assets/myfile.yaml. In the swagger embed code (javascript) I've tried a variety of approaches:
// in myswagger.html.erb
window.onload = function() {
const ui = SwaggerUIBundle({
url: "<%= asset_path('myfile.yaml') %>",
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset
]
})
}
I've also tried a bare path to /app/assets/myfile.yaml, document_path('myfile.yaml'), etc. But every time we end up with Fetch error Not Found /swagger.yaml.
What's the proper way to access this file and get it embedded in the javascript?
fast answer:
put the file yaml in your public folder
otherwise check what is generated at the browser level, by inspecting the page

Dynamic change servers url

I have web app that i deploy for multiple clients (lets say client1.com, client2.com and client3.com). I wrote REST API documentation using OA3 specification.
I have index.yaml which looks like:
openapi: 3.0.0
info:
title: REST API
description: REST API
version: 0.0.1
servers:
- url: http://client1.com/api
description: Something ...
tags: ...
and standard Swagger-ui index.html
// Begin Swagger UI call region
const ui = SwaggerUIBundle({
url: "docs/index.yaml",
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset.slice(1)
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
});
// End Swagger UI call region
window.ui = ui;
My problem is that i need to change servers.url depending on where and for which client i deploy app, so that each client can test API on his own servers and i don't want clients to see each other and know about each other in REST API docs.
How can i "dynamically" change / set server.url ? One "walkaround" solution is to copy index.yaml for each client and hardcode servers.url, but im sure there is better way which i don't see / know about.
Edit #1: given duplicate answer does not help because when i set servers to
servers:
- url: /api
swagger ui still points to http://localhost:8080/api/ but my app url is http://localhost:8080/myapp/. I could set servers: - url: /myapp/api but this is hardcoded value in index.yaml and that does not work for me. I need like "configurable" server url.
But thanks anyway
Edit #2: my current walkaround solution is to process yaml with server side code. In index.yaml i have:
servers:
- url: ##INSERT_SERVERS_TAG_HEREapi
and i replace ##INSERT_SERVERS_TAG_HERE with myapp.client.com/. But i'm still looking for some better solution.

Change default API spec URL in Swagger UI

I'm using the Swagger Editor Docker image for defining my API specification and generate a nodejs server to run as stub api and serve the documentation for my API spec.
I would like to know if it is possible to change the default URL to my own in order to present my spec when I open the page, and how I would do that.
For instance, I would like to change the default address to http://localhost:8080/spec
If I understand correctly, you used Swagger Codegen to generate a Node.js server. Now when you npm start and open Swagger UI, you want the input box (the spec URL) to display http://localhost:8080/spec instead of http://localhost/api-docs.
To change the path the .yaml spec is served from, edit your index.js as follows:
// 1 - add swaggerUi options
var uiOptions = {
apiDocs: '/spec' // <-- override the default /api-docs
};
swaggerTools.initializeMiddleware(swaggerDoc, function (middleware) {
...
// 2 - pass these options to swaggerUi
app.use(middleware.swaggerUi(uiOptions));
The port number is specified by the serverPort variable in index.js:
var serverPort = 8080;

API methods Sorting : Swagger version 3.0.2

I am using swagger version 3.0.2 , I have also followed this answer but there was no effect on the method order.
window.onload = function() {
const ui = SwaggerUIBundle({
.....
apisSorter: "alpha",
layout: "StandaloneLayout"
})
Can any one tell the best way to change the order of the API methods.
Swagger UI 3.0.7 added support for 2.x's operationsSorter parameter that controls method sorting inside each API/tag.
operationsSorter
Apply a sort to the operation list of each API. It can be 'alpha' (sort by paths alphanumerically), 'method' (sort by HTTP method) or a function (see Array.prototype.sort() to know how sort function works). Default is the order returned by the server unchanged.
const ui = SwaggerUIBundle({
url: "http://petstore.swagger.io/v2/swagger.json",
...
operationsSorter: "alpha"
})
The apisSorter parameter is not yet supported in 3.x.

Can't read from file issue in Swagger UI

I have incorporated swagger-ui in my application.
When I try and see the swagger-ui I get the documentation of the API nicely but after some time it shows some error icon at the button.
The Error message is like below:
[{"level":"error","message":"Can't read from file
http://MYIP/swagger/docs/v1"}]
I am not sure what is causing it. If I refresh it works and shows error after few seconds.
I am guessing "http://MYIP/swagger/docs/v1" is not publicly accessible.
By default swagger ui uses an online validator: online.swagger.io. If it cannot access your swagger url then you will see that error message.
Possible solutions:
Disable validation:
config.EnableSwagger().EnableSwaggerUi(c => c.DisableValidator());
Make your site publicly accessible
Host the validator locally:
You can get the validator from: https://github.com/swagger-api/validator-badge#running-locally
You will also need to tell swaggerui the location of the validator
config.EnableSwagger().EnableSwaggerUi(c => c.SetValidatorUrl(<validator_url>));
To supplement the accepted answer...I just uncommented one line in the SwaggerConfig.cs. I only wanted to get rid of the red error on the main swagger page by disabling the validator.
// By default, swagger-ui will validate specs against swagger.io's online validator and display the result
// in a badge at the bottom of the page. Use these options to set a different validator URL or to disable the
// feature entirely.
//c.SetValidatorUrl("http://localhost/validator");
c.DisableValidator();
If you are using files from swagger-ui github repo, then you can disable schema validation from your index.html file by setting validatorUrl to null in it:
window.onload = function() {
// Build a system
const ui = SwaggerUIBundle({
url: "/docs/open_api.json",
dom_id: '#swagger-ui',
validatorUrl : null, # <----- Add this line
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
})
If you using PHP Laravel framework with L5-Swagger just uncomment
'validatorUrl' => null,
from the config file /config/l5-swagger.php
Setting this.model.validatorUrl = null; in dist/swagger-ui.js worked for me ..
// Default validator
if(window.location.protocol === 'https:') {
//this.model.validatorUrl = 'https://online.swagger.io/validator';
this.model.validatorUrl = null;
} else {
//this.model.validatorUrl = 'http://online.swagger.io/validator';
this.model.validatorUrl = null;
}
To anynoe having similar issue when using Swashbuckle.OData:
I was having issues to integrated Swagger with our OData endpoints (using ODataController for API and Swashbuckle.OData NuGet package). I had to write our own document filter for it and add it:
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "OurSolution.API");
c.DocumentFilter<SwaggerDocumentFilter>();
//c.CustomProvider((defaultProvider) => new ODataSwaggerProvider(defaultProvider, c, GlobalConfiguration.Configuration));
c.IncludeXmlComments(GetXmlCommentsPath());
c.UseFullTypeNameInSchemaIds();
c.RootUrl(req => ConfigurationManager.AppSettings["AppUrl"]);
})
.EnableSwaggerUi(c =>
{
c.DisableValidator();
});
Apparently in order to avoid validation error I had to comment out line which is setting ODataSwaggerProvider along with turning off validator as mentioned in posts above. This makes usefulness of Swashbuckle.OData questionable yet I didn't test whatever it works with vanilla Swashbuckle.
Note: I used approach described on GitHub page for Swashbuckle.OData but it was not working: showing no possible endpoints at all. Maybe somebody knows better solution.

Resources