This commit is contained in:
2024-05-24 15:27:07 +03:00
parent 17df2ce6a9
commit fc1da2c238
643 changed files with 110185 additions and 231 deletions

View File

@@ -0,0 +1,24 @@
# Swagger UI
Welcome to the Swagger UI documentation!
## Usage
- [Installation](usage/installation.md)
- [Configuration](usage/configuration.md)
- [CORS](usage/cors.md)
- [OAuth2](usage/oauth2.md)
- [Deep Linking](usage/deep-linking.md)
- [Limitations](usage/limitations.md)
- [Version detection](usage/version-detection.md)
## Customization
- [Overview](customization/overview.md)
- [Plugin API](customization/plugin-api.md)
- [Custom layout](customization/custom-layout.md)
## Development
- [Setting up](development/setting-up.md)
- [Scripts](development/scripts.md)

View File

@@ -0,0 +1,3 @@
{
"title": "Swagger UI"
}

View File

@@ -0,0 +1,92 @@
# Creating a custom layout
**Layouts** are a special type of component that Swagger UI uses as the root component for the entire application. You can define custom layouts in order to have high-level control over what ends up on the page.
By default, Swagger UI uses `BaseLayout`, which is built into the application. You can specify a different layout to be used by passing the layout's name as the `layout` parameter to Swagger UI. Be sure to provide your custom layout as a component to Swagger UI.
<br>
For example, if you wanted to create a custom layout that only displayed operations, you could define an `OperationsLayout`:
```js
import React from "react"
// Create the layout component
class OperationsLayout extends React.Component {
render() {
const {
getComponent
} = this.props
const Operations = getComponent("operations", true)
return (
<div>
<Operations />
</div>
)
}
}
// Create the plugin that provides our layout component
const OperationsLayoutPlugin = () => {
return {
components: {
OperationsLayout: OperationsLayout
}
}
}
// Provide the plugin to Swagger-UI, and select OperationsLayout
// as the layout for Swagger-UI
SwaggerUI({
url: "https://petstore.swagger.io/v2/swagger.json",
plugins: [ OperationsLayoutPlugin ],
layout: "OperationsLayout"
})
```
### Augmenting the default layout
If you'd like to build around the `BaseLayout` instead of replacing it, you can pull the `BaseLayout` into your custom layout and use it:
```js
import React from "react"
// Create the layout component
class AugmentingLayout extends React.Component {
render() {
const {
getComponent
} = this.props
const BaseLayout = getComponent("BaseLayout", true)
return (
<div>
<div className="myCustomHeader">
<h1>I have a custom header above Swagger-UI!</h1>
</div>
<BaseLayout />
</div>
)
}
}
// Create the plugin that provides our layout component
const AugmentingLayoutPlugin = () => {
return {
components: {
AugmentingLayout: AugmentingLayout
}
}
}
// Provide the plugin to Swagger-UI, and select AugmentingLayout
// as the layout for Swagger-UI
SwaggerUI({
url: "https://petstore.swagger.io/v2/swagger.json",
plugins: [ AugmentingLayoutPlugin ],
layout: "AugmentingLayout"
})
```

View File

@@ -0,0 +1,71 @@
# Plugin system overview
### Prior art
Swagger UI leans heavily on concepts and patterns found in React and Redux.
If you aren't already familiar, here's some suggested reading:
- [React: Quick Start (reactjs.org)](https://reactjs.org/docs/hello-world.html)
- [Redux README (redux.js.org)](https://redux.js.org/)
In the following documentation, we won't take the time to define the fundamentals covered in the resources above.
> **Note**: Some of the examples in this section contain JSX, which is a syntax extension to JavaScript that is useful for writing React components.
>
> If you don't want to set up a build pipeline capable of translating JSX to JavaScript, take a look at [React without JSX (reactjs.org)](https://reactjs.org/docs/react-without-jsx.html). You can use our `system.React` reference to leverage React without needing to pull a copy into your project.
### The System
The _system_ is the heart of the Swagger UI application. At runtime, it's a JavaScript object that holds many things:
- React components
- Bound Redux actions and reducers
- Bound Reselect state selectors
- System-wide collection of available components
- Built-in helpers like `getComponent`, `makeMappedContainer`, and `getStore`
- References to the React and Immutable.js libraries (`system.React`, `system.Im`)
- User-defined helper functions
The system is built up when Swagger UI is called by iterating through ("compiling") each plugin that Swagger UI has been given, through the `presets` and `plugins` configuration options.
### Presets
Presets are arrays of plugins, which are provided to Swagger UI through the `presets` configuration option. All plugins within presets are compiled before any plugins provided via the `plugins` configuration option. Consider the following example:
```javascript
const MyPreset = [FirstPlugin, SecondPlugin, ThirdPlugin]
SwaggerUI({
presets: [
MyPreset
]
})
```
By default, Swagger UI includes the internal `ApisPreset`, which contains a set of plugins that provide baseline functionality for Swagger UI. If you specify your own `presets` option, you need to add the ApisPreset manually, like so:
```javascript
SwaggerUI({
presets: [
SwaggerUI.presets.apis,
MyAmazingCustomPreset
]
})
```
The need to provide the `apis` preset when adding other presets is an artifact of Swagger UI's original design, and will likely be removed in the next major version.
### getComponent
`getComponent` is a helper function injected into every container component, which is used to get references to components provided by the plugin system.
All components should be loaded through `getComponent`, since it allows other plugins to modify the component. It is preferred over a conventional `import` statement.
Container components in Swagger UI can be loaded by passing `true` as the second argument to `getComponent`, like so:
```javascript
getComponent("ContainerComponentName", true)
```
This will map the current system as props to the component.

View File

@@ -0,0 +1,415 @@
# 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:
```js
{
"dependencies": {
"swagger-ui": "~3.11.0"
}
}
```
### `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:
```js
const MultiplePhraseFilterPlugin = function() {
return {
fn: {
opsFilter: (taggedOps, phrase) => {
const phrases = phrase.split(", ")
return taggedOps.filter((val, key) => {
return phrases.some(item => key.indexOf(item) > -1)
})
}
}
}
}
```
### 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:
```jsx
import React from "react";
const MyLogoPlugin = {
components: {
Logo: () => (
<img alt="My Logo" height="40" src="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTM3IiBoZWlnaHQ9IjEzNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KCiA8Zz4KICA8dGl0bGU+TGF5ZXIgMTwvdGl0bGU+CiAgPHRleHQgdHJhbnNmb3JtPSJtYXRyaXgoMy40Nzc2OSAwIDAgMy4yNjA2NyAtNjczLjEyOCAtNjkxLjk5MykiIHN0cm9rZT0iIzAwMCIgZm9udC1zdHlsZT0ibm9ybWFsIiBmb250LXdlaWdodD0ibm9ybWFsIiB4bWw6c3BhY2U9InByZXNlcnZlIiB0ZXh0LWFuY2hvcj0ic3RhcnQiIGZvbnQtZmFtaWx5PSInT3BlbiBTYW5zIEV4dHJhQm9sZCciIGZvbnQtc2l6ZT0iMjQiIGlkPSJzdmdfMSIgeT0iMjQxLjIyMTkyIiB4PSIxOTYuOTY5MjEiIHN0cm9rZS13aWR0aD0iMCIgZmlsbD0iIzYyYTAzZiI+TXkgTG9nbzwvdGV4dD4KICA8cGF0aCBpZD0ic3ZnXzIiIGQ9Im0zOTUuNjAyNSw1MS4xODM1OWw1My44Nzc3MSwwbDE2LjY0ODYzLC01MS4xODM1OGwxNi42NDg2NCw1MS4xODM1OGw1My44Nzc3LDBsLTQzLjU4NzksMzEuNjMyODNsMTYuNjQ5NDksNTEuMTgzNThsLTQzLjU4NzkyLC0zMS42MzM2OWwtNDMuNTg3OTEsMzEuNjMzNjlsMTYuNjQ5NDksLTUxLjE4MzU4bC00My41ODc5MiwtMzEuNjMyODN6IiBzdHJva2Utd2lkdGg9IjAiIHN0cm9rZT0iIzAwMCIgZmlsbD0iIzYyYTAzZiIvPgogPC9nPgo8L3N2Zz4="/>
)
}
}
```
### 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 schemas type(eg. `string`, `array`, …) and if defined schemas format (eg. date, uuid, …) there is a corresponding component mapping:
**If format defined:**
```js
`JsonSchema_${type}_${format}`
```
**Fallback if `JsonSchema_${type}_${format}` component does not exist or format not defined:**
```js
`JsonSchema_${type}`
```
**Default:**
```js
`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](https://www.npmjs.com/package/react-datepicker) into swagger-ui.
All you need to do is to create a component to wrap [react-datepicker](https://www.npmjs.com/package/react-datepicker) accordingly to the format.
**There are two cases:**
- ```yaml
type: string
format: date
```
The resulting name for mapping to succeed: `JsonSchema_string_date`
- ```yaml
type: string
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:
```js
import React from "react";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
const JsonSchema_string_date = (props) => {
const dateNumber = Date.parse(props.value);
const date = dateNumber
? new Date(dateNumber)
: new Date();
return (
<DatePicker
selected={date}
onChange={d => props.onChange(d.toISOString().substring(0, 10))}
/>
);
}
const JsonSchema_string_date_time = (props) => {
const dateNumber = Date.parse(props.value);
const date = dateNumber
? new Date(dateNumber)
: new Date();
return (
<DatePicker
selected={date}
onChange={d => props.onChange(d.toISOString())}
showTimeSelect
timeFormat="p"
dateFormat="Pp"
/>
);
}
export const DateTimeSwaggerPlugin = {
components: {
JsonSchema_string_date: JsonSchema_string_date,
"JsonSchema_string_date-time": JsonSchema_string_date_time
}
};
```
### 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.
```js
// Add config to Request Snippets Configuration with an unique key like "node_native"
const snippetConfig = {
requestSnippetsEnabled: true,
requestSnippets: {
generators: {
"node_native": {
title: "NodeJs Native",
syntax: "javascript"
}
}
}
}
const SnippedGeneratorNodeJsPlugin = {
fn: {
// use `requestSnippetGenerator_` + key from config (node_native) for generator fn
requestSnippetGenerator_node_native: (request) => {
const url = new Url(request.get("url"))
let isMultipartFormDataRequest = false
const headers = request.get("headers")
if(headers && headers.size) {
request.get("headers").map((val, key) => {
isMultipartFormDataRequest = isMultipartFormDataRequest || /^content-type$/i.test(key) && /^multipart\/form-data$/i.test(val)
})
}
const packageStr = url.protocol === "https:" ? "https" : "http"
let reqBody = request.get("body")
if (request.get("body")) {
if (isMultipartFormDataRequest && ["POST", "PUT", "PATCH"].includes(request.get("method"))) {
return "throw new Error(\"Currently unsupported content-type: /^multipart\\/form-data$/i\");"
} else {
if (!Map.isMap(reqBody)) {
if (typeof reqBody !== "string") {
reqBody = JSON.stringify(reqBody)
}
} else {
reqBody = getStringBodyOfMap(request)
}
}
} else if (!request.get("body") && request.get("method") === "POST") {
reqBody = ""
}
const stringBody = "`" + (reqBody || "")
.replace(/\\n/g, "\n")
.replace(/`/g, "\\`")
+ "`"
return `const http = require("${packageStr}");
const options = {
"method": "${request.get("method")}",
"hostname": "${url.host}",
"port": ${url.port || "null"},
"path": "${url.pathname}"${headers && headers.size ? `,
"headers": {
${request.get("headers").map((val, key) => `"${key}": "${val}"`).valueSeq().join(",\n ")}
}` : ""}
};
const req = http.request(options, function (res) {
const chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});
${reqBody ? `\nreq.write(${stringBody});` : ""}
req.end();`
}
}
}
const ui = SwaggerUIBundle({
"dom_id": "#swagger-ui",
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl,
SnippedGeneratorNodeJsPlugin
],
layout: "StandaloneLayout",
validatorUrl: "https://validator.swagger.io/validator",
url: "https://petstore.swagger.io/v2/swagger.json",
...snippetConfig,
})
```
### 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:
```js
{
fn: {
componentDidCatch,
withErrorBoundary: withErrorBoundary(getSystem),
},
components: {
ErrorBoundary,
Fallback,
},
}
```
safe-render plugin is automatically utilized by [base](https://github.com/swagger-api/swagger-ui/blob/78f62c300a6d137e65fd027d850981b010009970/src/core/presets/base.js) and [standalone](https://github.com/swagger-api/swagger-ui/tree/78f62c300a6d137e65fd027d850981b010009970/src/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:
```js
[
"App",
"BaseLayout",
"VersionPragmaFilter",
"InfoContainer",
"ServersContainer",
"SchemesContainer",
"AuthorizeBtnContainer",
"FilterContainer",
"Operations",
"OperationContainer",
"parameters",
"responses",
"OperationServers",
"Models",
"ModelWrapper",
"Topbar",
"StandaloneLayout",
"onlineValidatorBadge"
]
```
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.
```js
const swaggerUI = SwaggerUI({
url: "https://petstore.swagger.io/v2/swagger.json",
dom_id: '#swagger-ui',
plugins: [
() => ({
components: {
MyCustomComponent1: () => 'my custom component',
},
}),
SwaggerUI.plugins.SafeRender({
fullOverride: true, // only the component list defined here will apply (not the default list)
componentList: [
"MyCustomComponent1",
],
}),
],
});
```
##### 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](https://reactjs.org/docs/error-boundaries.html#component-stack-traces).
It has precisely the same signature as error boundaries [componentDidCatch lifecycle method](https://reactjs.org/docs/react-component.html#componentdidcatch),
except it's a static function and not a class method.
Default implement of componentDidCatch uses `console.error` to display the received error:
```js
export const componentDidCatch = console.error;
```
To utilize your own error handling logic (e.g. [bugsnag](https://www.bugsnag.com/)), 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:
```js
import React from "react"
import PropTypes from "prop-types"
const Fallback = ({ name }) => (
<div className="fallback">
😱 <i>Could not render { name === "t" ? "this component" : name }, see the console.</i>
</div>
)
Fallback.propTypes = {
name: PropTypes.string.isRequired,
}
export default Fallback
```
Feel free to override it to match your look & feel:
```js
const CustomFallbackPlugin = () => ({
components: {
Fallback: ({ name } ) => `This is my custom fallback. ${name} failed to render`,
},
});
const swaggerUI = SwaggerUI({
url: "https://petstore.swagger.io/v2/swagger.json",
dom_id: '#swagger-ui',
plugins: [
CustomFallbackPlugin,
]
});
```
##### 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`.

View File

@@ -0,0 +1,459 @@
# Plugins
A plugin is a function that returns an object - more specifically, the object may contain functions and components that augment and modify Swagger UI's functionality.
### 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:
```js
{
"dependencies": {
"swagger-ui": "~3.11.0"
}
}
```
### Format
A plugin return value may contain any of these keys, where `stateKey` is a name for a piece of state:
```javascript
{
statePlugins: {
[stateKey]: {
actions,
reducers,
selectors,
wrapActions,
wrapSelectors
}
},
components: {},
wrapComponents: {},
rootInjects: {},
afterLoad: (system) => {},
fn: {},
}
```
### System is provided to plugins
Let's assume we have a plugin, `NormalPlugin`, that exposes a `doStuff` action under the `normal` state namespace.
```javascript
const ExtendingPlugin = function(system) {
return {
statePlugins: {
extending: {
actions: {
doExtendedThings: function(...args) {
// you can do other things in here if you want
return system.normalActions.doStuff(...args)
}
}
}
}
}
}
```
As you can see, each plugin is passed a reference to the `system` being built up. As long as `NormalPlugin` is compiled before `ExtendingPlugin`, this will work without any issues.
There is no dependency management built into the plugin system, so if you create a plugin that relies on another, it is your responsibility to make sure that the dependent plugin is loaded _after_ the plugin being depended on.
### Interfaces
#### Actions
```javascript
const MyActionPlugin = () => {
return {
statePlugins: {
example: {
actions: {
updateFavoriteColor: (str) => {
return {
type: "EXAMPLE_SET_FAV_COLOR",
payload: str
}
}
}
}
}
}
}
```
Once an action has been defined, you can use it anywhere that you can get a system reference:
```javascript
// elsewhere
system.exampleActions.updateFavoriteColor("blue")
```
The Action interface enables the creation of new Redux action creators within a piece of state in the Swagger UI system.
This action creator function will be exposed to container components as `exampleActions.updateFavoriteColor`. When this action creator is called, the return value (which should be a [Flux Standard Action](https://github.com/acdlite/flux-standard-action)) will be passed to the `example` reducer, which we'll define in the next section.
For more information about the concept of actions in Redux, see the [Redux Actions documentation](https://redux.js.org/tutorials/fundamentals/part-2-concepts-data-flow#actions).
#### Reducers
Reducers take a state (which is an [Immutable.js map](https://facebook.github.io/immutable-js/docs/#/Map)) and an action, then returns a new state.
Reducers must be provided to the system under the name of the action type that they handle, in this case, `EXAMPLE_SET_FAV_COLOR`.
```javascript
const MyReducerPlugin = function(system) {
return {
statePlugins: {
example: {
reducers: {
"EXAMPLE_SET_FAV_COLOR": (state, action) => {
// you're only working with the state under the namespace, in this case "example".
// So you can do what you want, without worrying about /other/ namespaces
return state.set("favColor", action.payload)
}
}
}
}
}
}
```
#### Selectors
Selectors reach into their namespace's state to retrieve or derive data from the state.
They're an easy way to keep logic in one place, and are preferred over passing state data directly into components.
```javascript
const MySelectorPlugin = function(system) {
return {
statePlugins: {
example: {
selectors: {
myFavoriteColor: (state) => state.get("favColor")
}
}
}
}
}
```
You can also use the Reselect library to memoize your selectors, which is recommended for any selectors that will see heavy use, since Reselect automatically memoizes selector calls for you:
```javascript
import { createSelector } from "reselect"
const MySelectorPlugin = function(system) {
return {
statePlugins: {
example: {
selectors: {
// this selector will be memoized after it is run once for a
// value of `state`
myFavoriteColor: createSelector((state) => state.get("favColor"))
}
}
}
}
}
```
Once a selector has been defined, you can use it anywhere that you can get a system reference:
```javascript
system.exampleSelectors.myFavoriteColor() // gets `favColor` in state for you
```
#### Components
You can provide a map of components to be integrated into the system.
Be mindful of the key names for the components you provide, as you'll need to use those names to refer to the components elsewhere.
```javascript
class HelloWorldClass extends React.Component {
render() {
return <h1>Hello World!</h1>
}
}
const MyComponentPlugin = function(system) {
return {
components: {
HelloWorldClass: HelloWorldClass
// components can just be functions, these are called "stateless components"
HelloWorldStateless: () => <h1>Hello World!</h1>,
}
}
}
```
```javascript
// elsewhere
const HelloWorldStateless = system.getComponent("HelloWorldStateless")
const HelloWorldClass = system.getComponent("HelloWorldClass")
```
You can also "cancel out" any components that you don't want by creating a stateless component that always returns `null`:
```javascript
const NeverShowInfoPlugin = function(system) {
return {
components: {
info: () => null
}
}
}
```
You can use `config.failSilently` if you don't want a warning when a component doesn't exist in the system.
Be mindful of `getComponent` arguments order. In the example below, the boolean `false` refers to presence of a container, and the 3rd argument is the config object used to suppress the missing component warning.
```javascript
const thisVariableWillBeNull = getComponent("not_real", false, { failSilently: true })
```
#### Wrap-Actions
Wrap Actions allow you to override the behavior of an action in the system.
They are function factories with the signature `(oriAction, system) => (...args) => result`.
A Wrap Action's first argument is `oriAction`, which is the action being wrapped. It is your responsibility to call the `oriAction` - if you don't, the original action will not fire!
This mechanism is useful for conditionally overriding built-in behaviors, or listening to actions.
```javascript
// FYI: in an actual Swagger UI, `updateSpec` is already defined in the core code
// it's just here for clarity on what's behind the scenes
const MySpecPlugin = function(system) {
return {
statePlugins: {
spec: {
actions: {
updateSpec: (str) => {
return {
type: "SPEC_UPDATE_SPEC",
payload: str
}
}
}
}
}
}
}
// this plugin allows you to watch changes to the spec that is in memory
const MyWrapActionPlugin = function(system) {
return {
statePlugins: {
spec: {
wrapActions: {
updateSpec: (oriAction, system) => (str) => {
// here, you can hand the value to some function that exists outside of Swagger UI
console.log("Here is my API definition", str)
return oriAction(str) // don't forget! otherwise, Swagger UI won't update
}
}
}
}
}
}
```
#### Wrap-Selectors
Wrap Selectors allow you to override the behavior of a selector in the system.
They are function factories with the signature `(oriSelector, system) => (state, ...args) => result`.
This interface is useful for controlling what data flows into components. We use this in the core code to disable selectors based on the API definition's version.
```javascript
import { createSelector } from 'reselect'
// FYI: in an actual Swagger UI, the `url` spec selector is already defined
// it's just here for clarity on what's behind the scenes
const MySpecPlugin = function(system) {
return {
statePlugins: {
spec: {
selectors: {
url: createSelector(
state => state.get("url")
)
}
}
}
}
}
const MyWrapSelectorsPlugin = function(system) {
return {
statePlugins: {
spec: {
wrapSelectors: {
url: (oriSelector, system) => (state, ...args) => {
console.log('someone asked for the spec url!!! it is', state.get('url'))
// you can return other values here...
// but let's just enable the default behavior
return oriSelector(state, ...args)
}
}
}
}
}
}
```
#### Wrap-Components
Wrap Components allow you to override a component registered within the system.
Wrap Components are function factories with the signature `(OriginalComponent, system) => props => ReactElement`. If you'd prefer to provide a React component class, `(OriginalComponent, system) => ReactClass` works as well.
```javascript
const MyWrapBuiltinComponentPlugin = function(system) {
return {
wrapComponents: {
info: (Original, system) => (props) => {
return <div>
<h3>Hello world! I am above the Info component.</h3>
<Original {...props} />
</div>
}
}
}
}
```
Here's another example that includes a code sample of a component that will be wrapped:
```javascript
///// Overriding a component from a plugin
// Here's our normal, unmodified component.
const MyNumberDisplayPlugin = function(system) {
return {
components: {
NumberDisplay: ({ number }) => <span>{number}</span>
}
}
}
// Here's a component wrapper defined as a function.
const MyWrapComponentPlugin = function(system) {
return {
wrapComponents: {
NumberDisplay: (Original, system) => (props) => {
if(props.number > 10) {
return <div>
<h3>Warning! Big number ahead.</h3>
<Original {...props} />
</div>
} else {
return <Original {...props} />
}
}
}
}
}
// Alternatively, here's the same component wrapper defined as a class.
const MyWrapComponentPlugin = function(system) {
return {
wrapComponents: {
NumberDisplay: (Original, system) => class WrappedNumberDisplay extends React.component {
render() {
if(props.number > 10) {
return <div>
<h3>Warning! Big number ahead.</h3>
<Original {...props} />
</div>
} else {
return <Original {...props} />
}
}
}
}
}
}
```
**Note:**
If you have multiple plugins wrapping the same component, you may want to change the [`pluginsOptions.pluginLoadType`](/docs/usage/configuration.md#Plugins-options) parameter to `chain`.
#### `rootInjects`
The `rootInjects` interface allows you to inject values at the top level of the system.
This interface takes an object, which will be merged in with the top-level system object at runtime.
```js
const MyRootInjectsPlugin = function(system) {
return {
rootInjects: {
myConstant: 123,
myMethod: (...params) => console.log(...params)
}
}
}
```
#### `afterLoad`
The `afterLoad` plugin method allows you to get a reference to the system after your plugin has been registered.
This interface is used in the core code to attach methods that are driven by bound selectors or actions. You can also use it to execute logic that requires your plugin to already be ready, for example fetching initial data from a remote endpoint and passing it to an action your plugin creates.
The plugin context, which is bound to `this`, is undocumented, but below is an example of how to attach a bound action as a top-level method:
```javascript
const MyMethodProvidingPlugin = function() {
return {
afterLoad(system) {
// at this point in time, your actions have been bound into the system
// so you can do things with them
this.rootInjects = this.rootInjects || {}
this.rootInjects.myMethod = system.exampleActions.updateFavoriteColor
},
statePlugins: {
example: {
actions: {
updateFavoriteColor: (str) => {
return {
type: "EXAMPLE_SET_FAV_COLOR",
payload: str
}
}
}
}
}
}
}
```
#### fn
The fn interface allows you to add helper functions to the system for use elsewhere.
```javascript
import leftPad from "left-pad"
const MyFnPlugin = function(system) {
return {
fn: {
leftPad: leftPad
}
}
}
```

View File

@@ -0,0 +1,39 @@
# Helpful scripts
Any of the scripts below can be run by typing `npm run <script name>` in the project's root directory.
### Developing
Script name | Description
--- | ---
`dev` | Spawn a hot-reloading dev server on port 3200.
`deps-check` | Generate a size and licensing report on Swagger UI's dependencies.
`lint` | Report ESLint style errors and warnings.
`lint-errors` | Report ESLint style errors, without warnings.
`lint-fix` | Attempt to fix style errors automatically.
`watch` | Rebuild the core files in `/dist` when the source code changes. Useful for `npm link` with Swagger Editor.
### Building
Script name | Description
--- | ---
`build` | Build a new set of JS and CSS assets, and output them to `/dist`.
`build-bundle` | Build `swagger-ui-bundle.js` only (commonJS).
`build-core` | Build `swagger-ui.(js\|css)` only (commonJS).
`build-standalone` | Build `swagger-ui-standalone-preset.js` only (commonJS).
`build-stylesheets` | Build `swagger-ui.css` only.
`build:es:bundle` | Build `swagger-ui-es-bundle.js` only (es2015).
`build:es:bundle:core` | Build `swagger-ui-es-bundle-core.js` only (es2015).
### Testing
Script name | Description
--- | ---
`test` | Run unit tests in Node, run Cypress end-to-end tests, and run ESLint in errors-only mode.
`just-test-in-node` | Run Mocha unit tests in Node.
`test:unit-jest` | Run Jest unit tests in Node.
`e2e` | Run end-to-end tests (requires JDK and Selenium).
`e2e-cypress` | Run end-to-end browser tests with Cypress.
`dev-e2e-cypress` | Dev mode, open Cypress runner and manually select tests to run.
`lint` | Run ESLint test
`test:artifact` | Run list of bundle artifact tests in Jest
`test:artifact:umd:bundle` | Run unit test that confirms `swagger-ui-bundle` exports as a Function
`test:artifact:es:bundle` | Run unit test that confirms `swagger-ui-es-bundle` exports as a Function
`test:artifact:es:bundle:core` | Run unit test that confirms `swagger-ui-es-bundle-core` exports as a Function

View File

@@ -0,0 +1,37 @@
# Setting up a dev environment
Swagger UI includes a development server that provides hot module reloading and unminified stack traces, for easier development.
### Prerequisites
- git, any version
- **Node.js >=16.13.2** and **npm >=8.1.2** are the minimum required versions that this repo runs on, but we recommend using the latest version of Node.js@16
### Steps
1. `git clone https://github.com/swagger-api/swagger-ui.git`
2. `cd swagger-ui`
3. `npm run dev`
4. Wait a bit
5. Open http://localhost:3200/
### Using your own local api definition with local dev build
You can specify a local file in `dev-helpers/swagger-initializer.js` by changing the `url` parameter. This local file MUST be located in the `dev-helpers` directory or a subdirectory. As a convenience and best practice, we recommend that you create a subdirectory, `dev-helpers/examples`, which is already specified in `.gitignore`.
replace
```
url: "https://petstore.swagger.io/v2/swagger.json",
```
with
```
url: "./examples/your-local-api-definition.yaml",
```
Files in `dev-helpers` should NOT be committed to git. The exception is if you are fixing something in `index.html`, `oauth2-redirect.html`, `swagger-initializer.js`, or introducing a new support file.
## Bonus points
- Swagger UI includes an ESLint rule definition. If you use a graphical editor, consider installing an ESLint plugin, which will point out syntax and style errors for you as you code.
- The linter runs as part of the PR test sequence, so don't think you can get away with not paying attention to it!

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

View File

@@ -0,0 +1,14 @@
### Demo of Swagger UI with Webpack.
This `webpack-getting-started` sample is for reference only.
It includes CSS and OAuth configuration.
`_sample_package.json` is a placeholder sample. You should rename this file, per `Usage` section below, and you should also verify and update this sample's `@latest` compared to the `swagger-ui@latest`
#### Usage
rename `_sample_package.json` to `package.json`
npm install
npm start

View File

@@ -0,0 +1,26 @@
{
"name": "swagger-ui-webpack-getting-started",
"version": "0.0.1",
"description": "A simple setup of Swagger UI with Webpack",
"scripts": {
"build": "webpack",
"start": "webpack-dev-server --open"
},
"author": "Shaun Luttin",
"license": "Apache-2.0",
"devDependencies": {
"clean-webpack-plugin": "^4.0.0",
"copy-webpack-plugin": "^11.0.0",
"html-webpack-plugin": "^5.5.0",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.11.0"
},
"dependencies": {
"css-loader": "^6.7.1",
"json-loader": "^0.5.7",
"style-loader": "^3.3.1",
"swagger-ui": "^4.14.0",
"yaml-loader": "^0.8.0"
}
}

View File

@@ -0,0 +1,10 @@
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Getting Started</title>
</head>
<body>
<div id="swagger"></div>
</body>
</html>

View File

@@ -0,0 +1,15 @@
import SwaggerUI from 'swagger-ui'
import 'swagger-ui/dist/swagger-ui.css';
const spec = require('./swagger-config.yaml');
const ui = SwaggerUI({
spec,
dom_id: '#swagger',
});
ui.initOAuth({
appName: "Swagger UI Webpack Demo",
// See https://demo.identityserver.io/ for configuration details.
clientId: 'implicit'
});

View File

@@ -0,0 +1,30 @@
openapi: "3.0.0"
info:
version: "0.0.1"
title: "Swagger UI Webpack Setup"
description: "Demonstrates Swagger UI with Webpack including CSS and OAuth"
servers:
- url: "https://demo.identityserver.io/api"
description: "Identity Server test API"
components:
securitySchemes:
# See https://demo.identityserver.io/ for configuration details.
identity_server_auth:
type: oauth2
flows:
implicit:
authorizationUrl: "https://demo.identityserver.io/connect/authorize"
scopes:
api: "api"
security:
- identity_server_auth:
- api
paths:
/test:
get:
summary: "Runs a test request against the Identity Server demo API"
responses:
401:
description: "Unauthorized"
200:
description: "OK"

View File

@@ -0,0 +1,52 @@
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const outputPath = path.resolve(__dirname, 'dist');
module.exports = {
mode: 'development',
entry: {
app: require.resolve('./src/index'),
},
resolve: {
extensions: ['.ts', '.js'],
},
module: {
rules: [
{
test: /\.yaml$/,
use: [
{ loader: 'json-loader' },
{ loader: 'yaml-loader', options:{ asJSON: true } }
]
},
{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' },
]
}
]
},
plugins: [
new CleanWebpackPlugin(),
new CopyWebpackPlugin({patterns:[
{
// Copy the Swagger OAuth2 redirect file to the project root;
// that file handles the OAuth2 redirect after authenticating the end-user.
from: require.resolve('swagger-ui/dist/oauth2-redirect.html'),
to: './'
}
]}),
new HtmlWebpackPlugin({
template: 'index.html'
})
],
output: {
filename: '[name].bundle.js',
path: outputPath,
}
};

View File

@@ -0,0 +1,391 @@
# Configuration
### How to configure
Swagger UI accepts configuration parameters in four locations.
From lowest to highest precedence:
- The `swagger-config.yaml` in the project root directory, if it exists, is baked into the application
- configuration object passed as an argument to Swagger UI (`SwaggerUI({ ... })`)
- configuration document fetched from a specified `configUrl`
- configuration items passed as key/value pairs in the URL query string
### Parameters
Parameters with dots in their names are single strings used to organize subordinate parameters, and are not indicative of a nested structure.
For readability, parameters are grouped by category and sorted alphabetically.
Type notations are formatted like so:
- `String=""` means a String type with a default value of `""`.
- `String=["a"*, "b", "c", "d"]` means a String type that can be `a`, `b`, `c`, or `d`, with the `*` indicating that `a` is the default value.
##### Core
Parameter name | Docker variable | Description
--- | --- | -----
<a name="configUrl"></a>`configUrl` | `CONFIG_URL` | `String`. URL to fetch external configuration document from.
<a name="dom_id"></a>`dom_id` | `DOM_ID` |`String`, **REQUIRED** if `domNode` is not provided. The ID of a DOM element inside which `SwaggerUI` will put its user interface.
<a name="domNode"></a>`domNode` | _Unavailable_ | `Element`, **REQUIRED** if `dom_id` is not provided. The HTML DOM element inside which `SwaggerUI` will put its user interface. Overrides `dom_id`.
<a name="spec"></a>`spec` | `SPEC` | `Object={}`. A JavaScript object describing the OpenAPI definition. When used, the `url` parameter will not be parsed. This is useful for testing manually-generated definitions without hosting them.
<a name="url"></a>`url` | `URL` | `String`. The URL pointing to API definition (normally `swagger.json` or `swagger.yaml`). Will be ignored if `urls` or `spec` is used.
<a name="urls"></a>`urls` | `URLS` | `Array`. An array of API definition objects (`[{url: "<url1>", name: "<name1>"},{url: "<url2>", name: "<name2>"}]`) used by Topbar plugin. When used and Topbar plugin is enabled, the `url` parameter will not be parsed. Names and URLs must be unique among all items in this array, since they're used as identifiers.
<a name="urls.primaryName"></a>`urls.primaryName` | `URLS_PRIMARY_NAME` | `String`. When using `urls`, you can use this subparameter. If the value matches the name of a spec provided in `urls`, that spec will be displayed when Swagger UI loads, instead of defaulting to the first spec in `urls`.
<a name="queryConfigEnabled"></a>`queryConfigEnabled` | `QUERY_CONFIG_ENABLED` | `Boolean=false`. Enables overriding configuration parameters via URL search params.
##### Plugin system
Read more about the plugin system in the [Customization documentation](/docs/customization/overview.md).
Parameter name | Docker variable | Description
--- | --- | -----
<a name="layout"></a>`layout` | _Unavailable_ | `String="BaseLayout"`. The name of a component available via the plugin system to use as the top-level layout for Swagger UI.
<a name="pluginsOptions"></a>`pluginsOptions` | _Unavailable_ | `Object`. A Javascript object to configure plugin integration and behaviors (see below).
<a name="plugins"></a>`plugins` | _Unavailable_ | `Array=[]`. An array of plugin functions to use in Swagger UI.
<a name="presets"></a>`presets` | _Unavailable_ | `Array=[SwaggerUI.presets.ApisPreset]`. An array of presets to use in Swagger UI. Usually, you'll want to include `ApisPreset` if you use this option.
##### Plugins options
Parameter name | Docker variable | Description
--- | --- | -----
<a name="pluginLoadType"></a>`pluginLoadType` | _Unavailable_ | `String=["legacy", "chain"]`. Control behavior of plugins when targeting the same component with wrapComponent.<br/>- `legacy` (default) : last plugin takes precedence over the others<br/>- `chain` : chain wrapComponents when targeting the same core component, allowing multiple plugins to wrap the same component
##### Display
<table role="table">
<thead>
<tr>
<th>Parameter name</th>
<th>Docker variable</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><a name="user-content-deeplinking"></a><code>deepLinking</code></td>
<td><code>DEEP_LINKING</code></td>
<td><code>Boolean=false</code>. If set to <code>true</code>, enables
deep linking for tags and operations. See the <a
href="/docs/usage/deep-linking.md">Deep Linking
documentation</a> for more information.
</td>
</tr>
<tr>
<td><a name="user-content-displayoperationid"></a><code>displayOperationId</code>
</td>
<td><code>DISPLAY_OPERATION_ID</code></td>
<td><code>Boolean=false</code>. Controls the display of operationId in
operations list. The default is <code>false</code>.
</td>
</tr>
<tr>
<td><a name="user-content-defaultmodelsexpanddepth"></a><code>defaultModelsExpandDepth</code>
</td>
<td><code>DEFAULT_MODELS_EXPAND_DEPTH</code></td>
<td><code>Number=1</code>. The default expansion depth for models (set
to -1 completely hide the models).
</td>
</tr>
<tr>
<td><a name="user-content-defaultmodelexpanddepth"></a><code>defaultModelExpandDepth</code>
</td>
<td><code>DEFAULT_MODEL_EXPAND_DEPTH</code></td>
<td><code>Number=1</code>. The default expansion depth for the model on
the model-example section.
</td>
</tr>
<tr>
<td><a name="user-content-defaultmodelrendering"></a><code>defaultModelRendering</code>
</td>
<td><code>DEFAULT_MODEL_RENDERING</code></td>
<td><code>String=["example"*, "model"]</code>. Controls how the model is
shown when the API is first rendered. (The user can always switch
the rendering for a given model by clicking the 'Model' and 'Example
Value' links.)
</td>
</tr>
<tr>
<td><a name="user-content-displayrequestduration"></a><code>displayRequestDuration</code>
</td>
<td><code>DISPLAY_REQUEST_DURATION</code></td>
<td><code>Boolean=false</code>. Controls the display of the request
duration (in milliseconds) for "Try it out" requests.
</td>
</tr>
<tr>
<td><a name="user-content-docexpansion"></a><code>docExpansion</code>
</td>
<td><code>DOC_EXPANSION</code></td>
<td><code>String=["list"*, "full", "none"]</code>. Controls the default
expansion setting for the operations and tags. It can be 'list'
(expands only the tags), 'full' (expands the tags and operations) or
'none' (expands nothing).
</td>
</tr>
<tr>
<td><a name="user-content-filter"></a><code>filter</code></td>
<td><code>FILTER</code></td>
<td><code>Boolean=false OR String</code>. If set, enables filtering. The
top bar will show an edit box that you can use to filter the tagged
operations that are shown. Can be Boolean to enable or disable, or a
string, in which case filtering will be enabled using that string as
the filter expression. Filtering is case sensitive matching the
filter expression anywhere inside the tag.
</td>
</tr>
<tr>
<td>
<a name="user-content-maxdisplayedtags"></a><code>maxDisplayedTags</code>
</td>
<td><code>MAX_DISPLAYED_TAGS</code></td>
<td><code>Number</code>. If set, limits the number of tagged operations
displayed to at most this many. The default is to show all
operations.
</td>
</tr>
<tr>
<td>
<a name="user-content-operationssorter"></a><code>operationsSorter</code>
</td>
<td><em>Unavailable</em></td>
<td><code>Function=(a =&gt; a)</code>. 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.
</td>
</tr>
<tr>
<td>
<a name="user-content-showextensions"></a><code>showExtensions</code>
</td>
<td><code>SHOW_EXTENSIONS</code></td>
<td><code>Boolean=false</code>. Controls the display of vendor extension
(<code>x-</code>) fields and values for Operations, Parameters,
Responses, and Schema.
</td>
</tr>
<tr>
<td><a name="user-content-showcommonextensions"></a><code>showCommonExtensions</code>
</td>
<td><code>SHOW_COMMON_EXTENSIONS</code></td>
<td><code>Boolean=false</code>. Controls the display of extensions
(<code>pattern</code>, <code>maxLength</code>,
<code>minLength</code>, <code>maximum</code>, <code>minimum</code>)
fields and values for Parameters.
</td>
</tr>
<tr>
<td><a name="user-content-tagsorter"></a><code>tagsSorter</code></td>
<td><em>Unavailable</em></td>
<td><code>Function=(a =&gt; a)</code>. Apply a sort to the tag list of
each API. It can be 'alpha' (sort by paths alphanumerically) or a
function (see <a
href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort"
rel="nofollow">Array.prototype.sort()</a> to learn how to
write a sort function). Two tag name strings are passed to the
sorter for each pass. Default is the order determined by Swagger UI.
</td>
</tr>
<tr>
<td>
<a name="user-content-useunsafemarkdown"></a><code>useUnsafeMarkdown</code>
</td>
<td><code>USE_UNSAFE_MARKDOWN</code></td>
<td><code>Boolean=false</code>. When enabled, sanitizer will leave
<code>style</code>, <code>class</code> and <code>data-*</code>
attributes untouched on all HTML Elements declared inside markdown
strings. This parameter is <strong>Deprecated</strong> and will be
removed in <code>4.0.0</code>.
</td>
</tr>
<tr>
<td><a name="user-content-oncomplete"></a><code>onComplete</code></td>
<td><em>Unavailable</em></td>
<td><code>Function=NOOP</code>. Provides a mechanism to be notified when
Swagger UI has finished rendering a newly provided definition.
</td>
</tr>
<tr>
<td>
<a name="user-content-syntaxhighlight"></a><code>syntaxHighlight</code>
</td>
<td><em>Unavailable</em></td>
<td>Set to <code>false</code> to deactivate syntax highlighting of
payloads and cURL command, can be otherwise an object with the
<code>activate</code> and <code>theme</code> properties.
</td>
</tr>
<tr>
<td><a name="user-content-syntaxhighlight.activate"></a><code>syntaxHighlight.activate</code>
</td>
<td><em>Unavailable</em></td>
<td><code>Boolean=true</code>. Whether syntax highlighting should be
activated or not.
</td>
</tr>
<tr>
<td><a name="user-content-syntaxhighlight.theme"></a><code>syntaxHighlight.theme</code>
</td>
<td><em>Unavailable</em></td>
<td><code>String=["agate"*, "arta", "monokai", "nord", "obsidian",
"tomorrow-night"]</code>. <a
href="https://highlightjs.org/static/demo/" rel="nofollow">Highlight.js</a>
syntax coloring theme to use. (Only these 6 styles are available.)
</td>
</tr>
<tr>
<td>
<a name="user-content-tryitoutenabled"></a><code>tryItOutEnabled</code>
</td>
<td><code>TRY_IT_OUT_ENABLED</code></td>
<td><code>Boolean=false</code>. Controls whether the "Try it out"
section should be enabled by default.
</td>
</tr>
<tr>
<td><a name="user-content-requestsnippetsenabled"></a><code>requestSnippetsEnabled</code>
</td>
<td><em>Unavailable</em></td>
<td><code>Boolean=false</code>. Enables the request snippet section.
When disabled, the legacy curl snippet will be used.
</td>
</tr>
<tr>
<td>
<a name="user-content-requestsnippets"></a><code>requestSnippets</code>
</td>
<td><em>Unavailable</em></td>
<td>
<pre lang="javascript">
<code>Object={
generators: {
curl_bash: {
title: "cURL (bash)",
syntax: "bash"
},
curl_powershell: {
title: "cURL (PowerShell)",
syntax: "powershell"
},
curl_cmd: {
title: "cURL (CMD)",
syntax: "bash"
},
},
defaultExpanded: true,
languages: null,
// e.g. only show curl bash = ["curl_bash"]
}
</code>
</pre>
This is the default configuration section for the the
requestSnippets plugin.
</td>
</tr>
</tbody>
</table>
##### Network
Parameter name | Docker variable | Description
--- | --- | -----
<a name="oauth2RedirectUrl"></a>`oauth2RedirectUrl` | `OAUTH2_REDIRECT_URL` | `String`. OAuth redirect URL.
<a name="requestInterceptor"></a>`requestInterceptor` | _Unavailable_ | `Function=(a => a)`. MUST be a function. Function to intercept remote definition, "Try it out", and OAuth 2.0 requests. Accepts one argument requestInterceptor(request) and must return the modified request, or a Promise that resolves to the modified request.
<a name="request.curlOptions"></a>`request.curlOptions` | _Unavailable_ | `Array`. If set, MUST be an array of command line options available to the `curl` command. This can be set on the mutated request in the `requestInterceptor` function. For example `request.curlOptions = ["-g", "--limit-rate 20k"]`
<a name="responseInterceptor"></a>`responseInterceptor` | _Unavailable_ | `Function=(a => a)`. MUST be a function. Function to intercept remote definition, "Try it out", and OAuth 2.0 responses. Accepts one argument responseInterceptor(response) and must return the modified response, or a Promise that resolves to the modified response.
<a name="showMutatedRequest"></a>`showMutatedRequest` | `SHOW_MUTATED_REQUEST` | `Boolean=true`. If set to `true`, uses the mutated request returned from a requestInterceptor to produce the curl command in the UI, otherwise the request before the requestInterceptor was applied is used.
<a name="supportedSubmitMethods"></a>`supportedSubmitMethods` | `SUPPORTED_SUBMIT_METHODS` | `Array=["get", "put", "post", "delete", "options", "head", "patch", "trace"]`. List of HTTP methods that have the "Try it out" feature enabled. An empty array disables "Try it out" for all operations. This does not filter the operations from the display.
<a name="validatorUrl"></a>`validatorUrl` | `VALIDATOR_URL` | `String="https://validator.swagger.io/validator" OR null`. By default, Swagger UI attempts to validate specs against swagger.io's online validator. You can use this parameter to set a different validator URL, for example for locally deployed validators ([Validator Badge](https://github.com/swagger-api/validator-badge)). Setting it to either `none`, `127.0.0.1` or `localhost` will disable validation.
<a name="withCredentials"></a>`withCredentials` | `WITH_CREDENTIALS` | `Boolean=false` If set to `true`, enables passing credentials, [as defined in the Fetch standard](https://fetch.spec.whatwg.org/#credentials), in CORS requests that are sent by the browser. Note that Swagger UI cannot currently set cookies cross-domain (see [swagger-js#1163](https://github.com/swagger-api/swagger-js/issues/1163)) - as a result, you will have to rely on browser-supplied cookies (which this setting enables sending) that Swagger UI cannot control.
##### Macros
Parameter name | Docker variable | Description
--- | --- | -----
<a name="modelPropertyMacro"></a>`modelPropertyMacro` | _Unavailable_ | `Function`. Function to set default values to each property in model. Accepts one argument modelPropertyMacro(property), property is immutable
<a name="parameterMacro"></a>`parameterMacro` | _Unavailable_ | `Function`. Function to set default value to parameters. Accepts two arguments parameterMacro(operation, parameter). Operation and parameter are objects passed for context, both remain immutable
##### Authorization
Parameter name | Docker variable | Description
--- | --- | -----
<a name="persistAuthorization"></a>`persistAuthorization` | `PERSIST_AUTHORIZATION` | `Boolean=false`. If set to `true`, it persists authorization data and it would not be lost on browser close/refresh
### Instance methods
**💡 Take note! These are methods, not parameters**.
Method name | Docker variable | Description
--- | --- | -----
<a name="initOAuth"></a>`initOAuth` | [_See `oauth2.md`_](./oauth2.md) | `(configObj) => void`. Provide Swagger UI with information about your OAuth server - see the [OAuth 2.0 documentation](./oauth2.md) for more information.
<a name="preauthorizeBasic"></a>`preauthorizeBasic` | _Unavailable_ | `(authDefinitionKey, username, password) => action`. Programmatically set values for a Basic authorization scheme.
<a name="preauthorizeApiKey"></a>`preauthorizeApiKey` | _Unavailable_ | `(authDefinitionKey, apiKeyValue) => action`. Programmatically set values for an API key or Bearer authorization scheme. In case of OpenAPI 3.0 Bearer scheme, `apiKeyValue` must contain just the token itself without the `Bearer` prefix.
### Docker
If you're using the Docker image, you can also control most of these options with environment variables. Each parameter has its environment variable name noted, if available.
Below are the general guidelines for using the environment variable interface.
##### String variables
Set the value to whatever string you'd like, taking care to escape characters where necessary
Example:
```sh
FILTER="myFilterValue"
LAYOUT="BaseLayout"
```
##### Boolean variables
Set the value to `true` or `false`.
Example:
```sh
DISPLAY_OPERATION_ID="true"
DEEP_LINKING="false"
```
##### Number variables
Set the value to _`n`_, where _n_ is the number you'd like to provide.
Example:
```sh
DEFAULT_MODELS_EXPAND_DEPTH="5"
DEFAULT_MODEL_EXPAND_DEPTH="7"
```
##### Array variables
Set the value to the literal array value you'd like, taking care to escape characters where necessary.
Example:
```sh
SUPPORTED_SUBMIT_METHODS="[\"get\", \"post\"]"
URLS="[ { url: \"https://petstore.swagger.io/v2/swagger.json\", name: \"Petstore\" } ]"
```
##### Object variables
Set the value to the literal object value you'd like, taking care to escape characters where necessary.
Example:
```sh
SPEC="{ \"openapi\": \"3.0.0\" }"
```
### Docker-Compose
#### .env file example encoding
```sh
SUPPORTED_SUBMIT_METHODS=['get', 'post']
URLS=[ { url: 'https://petstore.swagger.io/v2/swagger.json', name: 'Petstore' } ]
```

View File

@@ -0,0 +1,60 @@
# CORS
CORS is a technique to prevent websites from doing bad things with your personal data. Most browsers + JavaScript toolkits not only support CORS but enforce it, which has implications for your API server which supports Swagger.
You can read about CORS here: http://www.w3.org/TR/cors.
There are two cases where no action is needed for CORS support:
1. Swagger UI is hosted on the same server as the application itself (same host *and* port).
2. The application is located behind a proxy that enables the required CORS headers. This may already be covered within your organization.
Otherwise, CORS support needs to be enabled for:
1. Your Swagger docs. For Swagger 2.0 it's the `swagger.json`/`swagger.yaml` and any externally `$ref`ed docs.
2. For the `Try it now` button to work, CORS needs to be enabled on your API endpoints as well.
### Testing CORS Support
You can verify CORS support with one of three techniques:
- Curl your API and inspect the headers. For instance:
```bash
$ curl -I "https://petstore.swagger.io/v2/swagger.json"
HTTP/1.1 200 OK
Date: Sat, 31 Jan 2015 23:05:44 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, DELETE, PUT, PATCH, OPTIONS
Access-Control-Allow-Headers: Content-Type, api_key, Authorization
Content-Type: application/json
Content-Length: 0
```
This tells us that the petstore resource listing supports OPTIONS, and the following headers: `Content-Type`, `api_key`, `Authorization`.
- Try Swagger UI from your file system and look at the debug console. If CORS is not enabled, you'll see something like this:
```
XMLHttpRequest cannot load http://sad.server.com/v2/api-docs. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
```
Swagger UI cannot easily show this error state.
- Use the https://www.test-cors.org website to verify CORS support. Keep in mind this will show a successful result even if `Access-Control-Allow-Headers` is not available, which is still required for Swagger UI to function properly.
### Enabling CORS
The method of enabling CORS depends on the server and/or framework you use to host your application. https://enable-cors.org provides information on how to enable CORS in some common web servers.
Other servers/frameworks may provide you information on how to enable it specifically in their use case.
### CORS and Header Parameters
Swagger UI lets you easily send headers as parameters to requests. The name of these headers *MUST* be supported in your CORS configuration as well. From our example above:
```
Access-Control-Allow-Headers: Content-Type, api_key, Authorization
```
Only headers with these names will be allowed to be sent by Swagger UI.

View File

@@ -0,0 +1,36 @@
# `deepLinking` parameter
Swagger UI allows you to deeply link into tags and operations within a spec. When Swagger UI is provided a URL fragment at runtime, it will automatically expand and scroll to a specified tag or operation.
## Usage
👉🏼 Add `deepLinking: true` to your Swagger UI configuration to enable this functionality. This is demonstrated in [`dist/index.html`](https://github.com/swagger-api/swagger-ui/blob/master/dist/index.html).
When you expand a tag or operation, Swagger UI will automatically update its URL fragment with a deep link to the item.
Conversely, when you collapse a tag or operation, Swagger UI will clear the URL fragment.
You can also right-click a tag name or operation path to copy a link to that tag or operation.
#### Fragment format
The fragment is formatted in one of two ways:
- `#/{tagName}`, to trigger the focus of a specific tag
- `#/{tagName}/{operationId}`, to trigger the focus of a specific operation within a tag
`operationId` is the explicit operationId provided in the spec, if one exists.
Otherwise, Swagger UI generates an implicit operationId by combining the operation's path and method, while escaping non-alphanumeric characters.
## FAQ
> I'm using Swagger UI in an application that needs control of the URL fragment. How do I disable deep-linking?
This functionality is disabled by default, but you can pass `deepLinking: false` into Swagger UI as a configuration item to be sure.
> Can I link to multiple tags or operations?
No, this is not supported.
> Can I collapse everything except the operation or tag I'm linking to?
Sure - use `docExpansion: none` to collapse all tags and operations. Your deep link will take precedence over the setting, so only the tag or operation you've specified will be expanded.

View File

@@ -0,0 +1,178 @@
# Installation
## Distribution channels
### NPM Registry
We publish three modules to npm: **`swagger-ui`**, **`swagger-ui-dist`** and **`swagger-ui-react`**.
**`swagger-ui`** is meant for consumption by JavaScript web projects that include module bundlers,
such as Webpack, Browserify, and Rollup. Its main file exports Swagger UI's main function,
and the module also includes a namespaced stylesheet at `swagger-ui/dist/swagger-ui.css`. Here's an example:
```javascript
import SwaggerUI from 'swagger-ui'
// or use require if you prefer
const SwaggerUI = require('swagger-ui')
SwaggerUI({
dom_id: '#myDomId'
})
```
See the [Webpack Getting Started](../samples/webpack-getting-started) sample for details.
In contrast, **`swagger-ui-dist`** is meant for server-side projects that need assets to serve to clients. The module, when imported, includes an `absolutePath` helper function that returns the absolute filesystem path to where the `swagger-ui-dist` module is installed.
_Note: we suggest using `swagger-ui` when your tooling makes it possible, as `swagger-ui-dist`
will result in more code going across the wire._
The module's contents mirror the `dist` folder you see in the Git repository. The most useful file is `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 like so:
```javascript
const express = require('express')
const pathToSwaggerUi = require('swagger-ui-dist').absolutePath()
const app = express()
app.use(express.static(pathToSwaggerUi))
app.listen(3000)
```
The module also exports `SwaggerUIBundle` and `SwaggerUIStandalonePreset`, so
if you're in a JavaScript project that can't handle a traditional npm module,
you could do something like this:
```js
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"
})
```
`SwaggerUIBundle` is equivalent to `SwaggerUI`.
### Docker
You can pull a pre-built docker image of the swagger-ui directly from Docker Hub:
```
docker pull swaggerapi/swagger-ui
docker run -p 80:8080 swaggerapi/swagger-ui
```
Will start nginx with Swagger UI on port 80.
Or you can provide your own swagger.json on your host
```
docker run -p 80:8080 -e SWAGGER_JSON=/foo/swagger.json -v /bar:/foo swaggerapi/swagger-ui
```
You can also provide a URL to a swagger.json on an external host:
```
docker run -p 80:8080 -e SWAGGER_JSON_URL=https://petstore3.swagger.io/api/v3/openapi.json swaggerapi/swagger-ui
```
The base URL of the web application can be changed by specifying the `BASE_URL` environment variable:
```
docker run -p 80:8080 -e BASE_URL=/swagger -e SWAGGER_JSON=/foo/swagger.json -v /bar:/foo swaggerapi/swagger-ui
```
This will serve Swagger UI at `/swagger` instead of `/`.
For more information on controlling Swagger UI through the Docker image, see the Docker section of the [Configuration documentation](configuration.md#docker).
### unpkg
You can embed Swagger UI's code directly in your HTML by using [unpkg's](https://unpkg.com/) interface:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta
name="description"
content="SwaggerUI"
/>
<title>SwaggerUI</title>
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@4.5.0/swagger-ui.css" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://unpkg.com/swagger-ui-dist@4.5.0/swagger-ui-bundle.js" crossorigin></script>
<script>
window.onload = () => {
window.ui = SwaggerUIBundle({
url: 'https://petstore3.swagger.io/api/v3/openapi.json',
dom_id: '#swagger-ui',
});
};
</script>
</body>
</html>
```
Using `StandalonePreset` will render `TopBar` and `ValidatorBadge` as well.
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta
name="description"
content="SwaggerUI"
/>
<title>SwaggerUI</title>
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@4.5.0/swagger-ui.css" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://unpkg.com/swagger-ui-dist@4.5.0/swagger-ui-bundle.js" crossorigin></script>
<script src="https://unpkg.com/swagger-ui-dist@4.5.0/swagger-ui-standalone-preset.js" crossorigin></script>
<script>
window.onload = () => {
window.ui = SwaggerUIBundle({
url: 'https://petstore3.swagger.io/api/v3/openapi.json',
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
layout: "StandaloneLayout",
});
};
</script>
</body>
</html>
```
See [unpkg's main page](https://unpkg.com/) for more information on how to use unpkg.
### Static files without HTTP or HTML
Once swagger-ui has successfully generated the `/dist` directory, you can copy this to your own file system and host from there.
## Plain old HTML/CSS/JS (Standalone)
The folder `/dist` includes all the HTML, CSS and JS files needed to run SwaggerUI on a static website or CMS, without requiring NPM.
1. Download the [latest release](https://github.com/swagger-api/swagger-ui/releases/latest).
1. Copy the contents of the `/dist` folder to your server.
1. Open `swagger-initializer.js` in your text editor and replace "https://petstore.swagger.io/v2/swagger.json" with the URL for your OpenAPI 3.0 spec.

View File

@@ -0,0 +1,38 @@
# Limitations
### Forbidden header names
Some header names cannot be controlled by web applications, due to security
features built into web browsers.
Forbidden headers include:
> - Accept-Charset
> - Accept-Encoding
> - Access-Control-Request-Headers
> - Access-Control-Request-Method
> - Connection
> - Content-Length
> - Cookie
> - Cookie2
> - Date
> - DNT
> - Expect
> - Host
> - Keep-Alive
> - Origin
> - Proxy-*
> - Sec-*
> - Referer
> - TE
> - Trailer
> - Transfer-Encoding
> - Upgrade
> - Via
>
> _[Forbidden header names (developer.mozilla.org)](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name)_
The biggest impact of this is that OpenAPI 3.0 Cookie parameters cannot be
controlled when running Swagger UI in a browser.
For more context, see [#3956](https://github.com/swagger-api/swagger-ui/issues/3956).

View File

@@ -0,0 +1,31 @@
# OAuth 2.0 configuration
You can configure OAuth 2.0 authorization by calling the `initOAuth` method.
Property name | Docker variable | Description
--- | --- | ------
clientId | `OAUTH_CLIENT_ID` | Default clientId. MUST be a string
clientSecret | `OAUTH_CLIENT_SECRET` | **🚨 Never use this parameter in your production environment. It exposes crucial security information. This feature is intended for dev/test environments only. 🚨** <br>Default clientSecret. MUST be a string
realm | `OAUTH_REALM` |realm query parameter (for oauth1) added to `authorizationUrl` and `tokenUrl`. MUST be a string
appName | `OAUTH_APP_NAME` |application name, displayed in authorization popup. MUST be a string
scopeSeparator | `OAUTH_SCOPE_SEPARATOR` |scope separator for passing scopes, encoded before calling, default value is a space (encoded value `%20`). MUST be a string
scopes | `OAUTH_SCOPES` |string array or scope separator (i.e. space) separated string of initially selected oauth scopes, default is empty array
additionalQueryStringParams | `OAUTH_ADDITIONAL_PARAMS` |Additional query parameters added to `authorizationUrl` and `tokenUrl`. MUST be an object
useBasicAuthenticationWithAccessCodeGrant | `OAUTH_USE_BASIC_AUTH` |Only activated for the `accessCode` flow. During the `authorization_code` request to the `tokenUrl`, pass the [Client Password](https://tools.ietf.org/html/rfc6749#section-2.3.1) using the HTTP Basic Authentication scheme (`Authorization` header with `Basic base64encode(client_id + client_secret)`). The default is `false`
usePkceWithAuthorizationCodeGrant | `OAUTH_USE_PKCE` | Only applies to `Authorization Code` flows. [Proof Key for Code Exchange](https://tools.ietf.org/html/rfc7636) brings enhanced security for OAuth public clients. The default is `false` <br/><br/>_Note:_ This option does not hide the client secret input because [neither PKCE nor client secrets are replacements for each other](https://oauth.net/2/pkce/).
```javascript
const ui = SwaggerUI({...})
// Method can be called in any place after calling constructor SwaggerUIBundle
ui.initOAuth({
clientId: "your-client-id",
clientSecret: "your-client-secret-if-required",
realm: "your-realms",
appName: "your-app-name",
scopeSeparator: " ",
scopes: "openid profile",
additionalQueryStringParams: {test: "hello"},
useBasicAuthenticationWithAccessCodeGrant: true,
usePkceWithAuthorizationCodeGrant: true
})
```

View File

@@ -0,0 +1,54 @@
# Detecting your Swagger UI version
At times, you're going to need to know which version of Swagger UI you use.
The first step would be to detect which major version you currently use, as the method of detecting the version has changed. If your Swagger UI has been heavily modified and you cannot detect from the look and feel which major version you use, you'd have to try both methods to get the exact version.
To help you visually detect which version you're using, we've included supporting images.
# Swagger UI 3.x
![Swagger UI 3](/docs/images/swagger-ui3.png)
Some distinct identifiers to Swagger UI 3.x:
- The API version appears as a badge next to its title.
- If there are schemes or authorizations, they'd appear in a bar above the operations.
- Try it out functionality is not enabled by default.
- All the response codes in the operations appear at after the parameters.
- There's a models section after the operations.
If you've determined this is the version you have, to find the exact version:
- Open your browser's web console (changes between browsers)
- Type `JSON.stringify(versions)` in the console and execute the call.
- The result should look similar to `swaggerUi : Object { version: "3.1.6", gitRevision: "g786cd47", gitDirty: true, … }`.
- The version taken from that example would be `3.1.6`.
Note: This functionality was added in 3.0.8. If you're unable to execute it, you're likely to use an older version, and in that case the first step would be to upgrade.
# Swagger UI 2.x and under
![Swagger UI 2](/docs/images/swagger-ui2.png)
Some distinct identifiers to Swagger UI 2.x:
- The API version appears at the bottom of the page.
- Schemes are not rendered.
- Authorization, if rendered, will appear next to the navigation bar.
- Try it out functionality is enabled by default.
- The successful response code would appear above the parameters, the rest below them.
- There's no models section after the operations.
If you've determined this is the version you have, to find the exact version:
- Navigate to the sources of the UI. Either on your disk or via the view page source functionality in your browser.
- Find an open the `swagger-ui.js`
- At the top of the page, there would be a comment containing the exact version of Swagger UI. This example shows version `2.2.9`:
```
/**
* swagger-ui - Swagger UI is a dependency-free collection of HTML, JavaScript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API
* @version v2.2.9
* @link https://swagger.io
* @license Apache-2.0
*/
```