Skip to content

Plug points

Swagger UI exposes most of its internal logic through the plugin system.

Often, it is beneficial to override the core internals to achieve custom behavior.

Note: Semantic Versioning

Swagger UI’s internal APIs are not part of our public contract, which means that they can change without the major version change.

If your custom plugins wrap, extend, override, or consume any internal core APIs, we recommend specifying a specific minor version of Swagger UI to use in your application, because they will not change between patch versions.

If you’re installing Swagger UI via NPM, for example, you can do this by using a tilde:

1
{
2
"dependencies": {
3
"swagger-ui": "~3.11.0"
4
}
5
}

fn.opsFilter

When using the filter option, tag names will be filtered by the user-provided value. If you’d like to customize this behavior, you can override the default opsFilter function.

For example, you can implement a multiple-phrase filter:

1
const MultiplePhraseFilterPlugin = function() {
2
return {
3
fn: {
4
opsFilter: (taggedOps, phrase) => {
5
const phrases = phrase.split(", ")
6
7
return taggedOps.filter((val, key) => {
8
return phrases.some(item => key.indexOf(item) > -1)
9
})
10
}
11
}
12
}
13
}

Logo component

While using the Standalone Preset the SwaggerUI logo is rendered in the Top Bar. The logo can be exchanged by replacing the Logo component via the plugin api:

1
import React from "react";
2
const MyLogoPlugin = {
3
components: {
4
Logo: () => (
5
<img alt="My Logo" height="40" src="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTM3IiBoZWlnaHQ9IjEzNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KCiA8Zz4KICA8dGl0bGU+TGF5ZXIgMTwvdGl0bGU+CiAgPHRleHQgdHJhbnNmb3JtPSJtYXRyaXgoMy40Nzc2OSAwIDAgMy4yNjA2NyAtNjczLjEyOCAtNjkxLjk5MykiIHN0cm9rZT0iIzAwMCIgZm9udC1zdHlsZT0ibm9ybWFsIiBmb250LXdlaWdodD0ibm9ybWFsIiB4bWw6c3BhY2U9InByZXNlcnZlIiB0ZXh0LWFuY2hvcj0ic3RhcnQiIGZvbnQtZmFtaWx5PSInT3BlbiBTYW5zIEV4dHJhQm9sZCciIGZvbnQtc2l6ZT0iMjQiIGlkPSJzdmdfMSIgeT0iMjQxLjIyMTkyIiB4PSIxOTYuOTY5MjEiIHN0cm9rZS13aWR0aD0iMCIgZmlsbD0iIzYyYTAzZiI+TXkgTG9nbzwvdGV4dD4KICA8cGF0aCBpZD0ic3ZnXzIiIGQ9Im0zOTUuNjAyNSw1MS4xODM1OWw1My44Nzc3MSwwbDE2LjY0ODYzLC01MS4xODM1OGwxNi42NDg2NCw1MS4xODM1OGw1My44Nzc3LDBsLTQzLjU4NzksMzEuNjMyODNsMTYuNjQ5NDksNTEuMTgzNThsLTQzLjU4NzkyLC0zMS42MzM2OWwtNDMuNTg3OTEsMzEuNjMzNjlsMTYuNjQ5NDksLTUxLjE4MzU4bC00My41ODc5MiwtMzEuNjMyODN6IiBzdHJva2Utd2lkdGg9IjAiIHN0cm9rZT0iIzAwMCIgZmlsbD0iIzYyYTAzZiIvPgogPC9nPgo8L3N2Zz4="/>
6
)
7
}
8
}

JSON Schema components

In swagger there are so called JSON Schema components. These are used to render inputs for parameters and components of request bodies with application/x-www-form-urlencoded or multipart/* media-type.

Internally swagger uses following mapping to find the JSON Schema component from OpenAPI Specification schema information:

For each schema’s type(eg. string, array, …) and if defined schema’s format (eg. ‘date’, ‘uuid’, …) there is a corresponding component mapping:

If format defined:

1
`JsonSchema_${type}_${format}`

Fallback if JsonSchema_${type}_${format} component does not exist or format not defined:

1
`JsonSchema_${type}`

Default:

1
`JsonSchema_string`

With this, one can define custom input components or override existing.

Example Date-Picker plugin

If one would like to input date values you could provide a custom plugin to integrate react-datepicker into swagger-ui. All you need to do is to create a component to wrap react-datepicker accordingly to the format.

There are two cases:

  • 1
    type: string
    2
    format: date
    The resulting name for mapping to succeed: JsonSchema_string_date
  • 1
    type: string
    2
    format: date-time
    The resulting name for mapping to succeed: JsonSchema_string_date-time

This creates the need for two components and simple logic to strip any time input in case the format is date:

1
import React from "react";
2
import DatePicker from "react-datepicker";
3
import "react-datepicker/dist/react-datepicker.css";
4
5
const JsonSchema_string_date = (props) => {
6
const dateNumber = Date.parse(props.value);
7
const date = dateNumber
8
? new Date(dateNumber)
9
: new Date();
10
11
return (
12
<DatePicker
13
selected={date}
14
onChange={d => props.onChange(d.toISOString().substring(0, 10))}
15
/>
16
);
17
}
18
19
const JsonSchema_string_date_time = (props) => {
20
const dateNumber = Date.parse(props.value);
21
const date = dateNumber
22
? new Date(dateNumber)
23
: new Date();
24
25
return (
26
<DatePicker
27
selected={date}
28
onChange={d => props.onChange(d.toISOString())}
29
showTimeSelect
30
timeFormat="p"
31
dateFormat="Pp"
32
/>
33
);
34
}
35
36
37
export const DateTimeSwaggerPlugin = {
38
components: {
39
JsonSchema_string_date: JsonSchema_string_date,
40
"JsonSchema_string_date-time": JsonSchema_string_date_time
41
}
42
};

Request Snippets

SwaggerUI can be configured with the requestSnippetsEnabled: true option to activate Request Snippets.
Instead of the generic curl that is generated upon doing a request. It gives you more granular options:

  • curl for bash
  • curl for cmd
  • curl for powershell

There might be the case where you want to provide your own snipped generator. This can be done by using the plugin api.
A Request Snipped generator consists of the configuration and a fn,
which takes the internal request object and transforms it to the desired snippet.

1
// Add config to Request Snippets Configuration with an unique key like "node_native"
2
const snippetConfig = {
3
requestSnippetsEnabled: true,
4
requestSnippets: {
5
generators: {
6
"node_native": {
7
title: "NodeJs Native",
8
syntax: "javascript"
9
}
10
}
11
}
12
}
13
14
const SnippedGeneratorNodeJsPlugin = {
15
fn: {
16
// use `requestSnippetGenerator_` + key from config (node_native) for generator fn
17
requestSnippetGenerator_node_native: (request) => {
18
const url = new Url(request.get("url"))
19
let isMultipartFormDataRequest = false
20
const headers = request.get("headers")
21
if(headers && headers.size) {
22
request.get("headers").map((val, key) => {
23
isMultipartFormDataRequest = isMultipartFormDataRequest || /^content-type$/i.test(key) && /^multipart\/form-data$/i.test(val)
24
})
25
}
26
const packageStr = url.protocol === "https:" ? "https" : "http"
27
let reqBody = request.get("body")
28
if (request.get("body")) {
29
if (isMultipartFormDataRequest && ["POST", "PUT", "PATCH"].includes(request.get("method"))) {
30
return "throw new Error(\"Currently unsupported content-type: /^multipart\\/form-data$/i\");"
31
} else {
32
if (!Map.isMap(reqBody)) {
33
if (typeof reqBody !== "string") {
34
reqBody = JSON.stringify(reqBody)
35
}
36
} else {
37
reqBody = getStringBodyOfMap(request)
38
}
39
}
40
} else if (!request.get("body") && request.get("method") === "POST") {
41
reqBody = ""
42
}
43
44
const stringBody = "`" + (reqBody || "")
45
.replace(/\\n/g, "\n")
46
.replace(/`/g, "\\`")
47
+ "`"
48
49
return `const http = require("${packageStr}");
50
const options = {
51
"method": "${request.get("method")}",
52
"hostname": "${url.host}",
53
"port": ${url.port || "null"},
54
"path": "${url.pathname}"${headers && headers.size ? `,
55
"headers": {
56
${request.get("headers").map((val, key) => `"${key}": "${val}"`).valueSeq().join(",\n ")}
57
}` : ""}
58
};
59
const req = http.request(options, function (res) {
60
const chunks = [];
61
res.on("data", function (chunk) {
62
chunks.push(chunk);
63
});
64
res.on("end", function () {
65
const body = Buffer.concat(chunks);
66
console.log(body.toString());
67
});
68
});
69
${reqBody ? `\nreq.write(${stringBody});` : ""}
70
req.end();`
71
}
72
}
73
}
74
75
const ui = SwaggerUIBundle({
76
"dom_id": "#swagger-ui",
77
deepLinking: true,
78
presets: [
79
SwaggerUIBundle.presets.apis,
80
SwaggerUIStandalonePreset
81
],
82
plugins: [
83
SwaggerUIBundle.plugins.DownloadUrl,
84
SnippedGeneratorNodeJsPlugin
85
],
86
layout: "StandaloneLayout",
87
validatorUrl: "https://validator.swagger.io/validator",
88
url: "https://petstore.swagger.io/v2/swagger.json",
89
...snippetConfig,
90
})

Error handling

SwaggerUI comes with a safe-render plugin that handles error handling allows plugging into error handling system and modify it.

The plugin accepts a list of component names that should be protected by error boundaries.

Its public API looks like this:

1
{
2
fn: {
3
componentDidCatch,
4
withErrorBoundary: withErrorBoundary(getSystem),
5
},
6
components: {
7
ErrorBoundary,
8
Fallback,
9
},
10
}

safe-render plugin is automatically utilized by base and standalone SwaggerUI presets and should always be used as the last plugin, after all the components are already known to the SwaggerUI. The plugin defines a default list of components that should be protected by error boundaries:

1
[
2
"App",
3
"BaseLayout",
4
"VersionPragmaFilter",
5
"InfoContainer",
6
"ServersContainer",
7
"SchemesContainer",
8
"AuthorizeBtnContainer",
9
"FilterContainer",
10
"Operations",
11
"OperationContainer",
12
"parameters",
13
"responses",
14
"OperationServers",
15
"Models",
16
"ModelWrapper",
17
"Topbar",
18
"StandaloneLayout",
19
"onlineValidatorBadge"
20
]

As demonstrated below, additional components can be protected by utilizing the safe-render plugin with configuration options. This gets really handy if you are a SwaggerUI integrator and you maintain a number of plugins with additional custom components.

1
const swaggerUI = SwaggerUI({
2
url: "https://petstore.swagger.io/v2/swagger.json",
3
dom_id: '#swagger-ui',
4
plugins: [
5
() => ({
6
components: {
7
MyCustomComponent1: () => 'my custom component',
8
},
9
}),
10
SwaggerUI.plugins.SafeRender({
11
fullOverride: true, // only the component list defined here will apply (not the default list)
12
componentList: [
13
"MyCustomComponent1",
14
],
15
}),
16
],
17
});
componentDidCatch

This static function is invoked after a component has thrown an error.
It receives two parameters:

  1. error - The error that was thrown.
  2. info - An object with a componentStack key containing information about which component threw the error.

It has precisely the same signature as error boundaries componentDidCatch lifecycle method, except it’s a static function and not a class method.

Default implement of componentDidCatch uses console.error to display the received error:

1
export const componentDidCatch = console.error;

To utilize your own error handling logic (e.g. bugsnag), create new SwaggerUI plugin that overrides componentDidCatch:

{% highlight js linenos %} const BugsnagErrorHandlerPlugin = () => { // init bugsnag

return { fn: { componentDidCatch = (error, info) => { Bugsnag.notify(error); Bugsnag.notify(info); }, }, }; }; {% endhighlight %}

withErrorBoundary

This function is HOC (Higher Order Component). It wraps a particular component into the ErrorBoundary component. It can be overridden via a plugin system to control how components are wrapped by the ErrorBoundary component. In 99.9% of situations, you won’t need to override this function, but if you do, please read the source code of this function first.

Fallback

The component is displayed when the error boundary catches an error. It can be overridden via a plugin system. Its default implementation is trivial:

1
import React from "react"
2
import PropTypes from "prop-types"
3
4
const Fallback = ({ name }) => (
5
<div className="fallback">
6
😱 <i>Could not render { name === "t" ? "this component" : name }, see the console.</i>
7
</div>
8
)
9
Fallback.propTypes = {
10
name: PropTypes.string.isRequired,
11
}
12
export default Fallback

Feel free to override it to match your look & feel:

1
const CustomFallbackPlugin = () => ({
2
components: {
3
Fallback: ({ name } ) => `This is my custom fallback. ${name} failed to render`,
4
},
5
});
6
7
const swaggerUI = SwaggerUI({
8
url: "https://petstore.swagger.io/v2/swagger.json",
9
dom_id: '#swagger-ui',
10
plugins: [
11
CustomFallbackPlugin,
12
]
13
});
ErrorBoundary

This is the component that implements React error boundaries. Uses componentDidCatch and Fallback under the hood. In 99.9% of situations, you won’t need to override this component, but if you do, please read the source code of this component first.

Change in behavior

In prior releases of SwaggerUI (before v4.3.0), almost all components have been protected, and when thrown error, Fallback component was displayed. This changes with SwaggerUI v4.3.0. Only components defined by the safe-render plugin are now protected and display fallback. If a small component somewhere within SwaggerUI React component tree fails to render and throws an error. The error bubbles up to the closest error boundary, and that error boundary displays the Fallback component and invokes componentDidCatch.