### Development Environment Setup Steps
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/development/setting-up.md
Commands to clone the Swagger UI repository, install dependencies, initialize Husky (optional), and start the development server.
```bash
git clone https://github.com/swagger-api/swagger-ui.git
cd swagger-ui
npm install
npx husky init
npm run dev
```
--------------------------------
### Package JSON Setup
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/samples/webpack-getting-started/README.md
This snippet shows the necessary steps to set up the project's package.json file and install dependencies using npm. It involves renaming a placeholder file and executing standard npm commands for project initialization and execution.
```bash
rename "_sample_package.json" to "package.json"
npm install
npm start
```
--------------------------------
### Install swagger-ui-react
Source: https://github.com/swagger-api/swagger-ui/blob/master/flavors/swagger-ui-react/README.md
Installs the swagger-ui-react package using npm. This is the primary step to integrate the component into a React project.
```bash
$ npm install swagger-ui-react
```
--------------------------------
### Use Swagger UI React with JSON Schema Samples (JavaScript)
Source: https://github.com/swagger-api/swagger-ui/wiki/JSON-Schema-samples-API
Illustrates the integration of Swagger UI React for generating JSON Schema samples. This example shows the setup process using the System constructor and accessing schema generation functions for different JSON Schema drafts.
```javascript
import SwaggerUI from 'swagger-ui-react';
const system = new SwaggerUI.System({
plugins: [
SwaggerUI.plugins.JSONSchema5Samples,
SwaggerUI.plugins.JSONSchema202012Samples
],
presets: [],
}).getSystem();
system.fn.jsonSchema5.getJsonSampleSchema({ type: "object", properties: { a: { type: "string" }} });
system.fn.jsonSchema202012.getJsonSampleSchema({ type: "object", properties: { a: { type: "string" }} });
```
--------------------------------
### Install Swagger UI NPM Packages
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/installation.md
Installs the core `swagger-ui`, `swagger-ui-react`, and `swagger-ui-dist` packages from the NPM registry. These packages are essential for integrating Swagger UI into web projects or serving its assets.
```sh
npm install swagger-ui
```
```sh
npm install swagger-ui-react
```
```sh
npm install swagger-ui-dist
```
--------------------------------
### Swagger UI Schema Format Examples
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/customization/plug-points.md
YAML examples illustrating schema definitions for date and date-time formats in Swagger UI, which map to specific custom components.
```yaml
type: string
format: date
```
```yaml
type: string
format: date-time
```
--------------------------------
### Configure Swagger UI for Static File Hosting
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/installation.md
Instructions for hosting Swagger UI from static files. This involves downloading the latest release, copying the `/dist` folder, and modifying the `swagger-initializer.js` file to point to your OpenAPI specification.
```text
1. Download the latest release of Swagger UI.
2. Copy the contents of the `/dist` folder to your server.
3. Open `swagger-initializer.js` in a text editor.
4. Replace "https://petstore.swagger.io/v2/swagger.json" with the URL for your OpenAPI 3.0 spec.
```
--------------------------------
### Swagger UI Plugin Dependency Management Example
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/customization/plugin-api.md
Illustrates how one plugin can extend the functionality of another by calling its actions, emphasizing the need for proper loading order.
```javascript
const NormalPlugin = function(system) {
return {
statePlugins: {
normal: {
actions: {
doStuff: function(...args) {
console.log('Doing stuff...');
// ... actual logic ...
return { type: 'NORMAL_STUFF_DONE' };
}
}
}
}
}
}
const ExtendingPlugin = function(system) {
return {
statePlugins: {
extending: {
actions: {
doExtendedThings: function(...args) {
// This plugin relies on 'doStuff' from 'NormalPlugin'
// It's crucial that NormalPlugin is loaded before ExtendingPlugin.
return system.normalActions.doStuff(...args);
}
}
}
}
}
}
```
--------------------------------
### Embed Swagger UI with unpkg
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/installation.md
Embeds Swagger UI directly into an HTML page using CDN links from unpkg. This example shows the basic setup for displaying an OpenAPI specification.
```html
SwaggerUI
```
--------------------------------
### Basic Swagger UI Initialization (swagger-ui package)
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/installation.md
Demonstrates how to import and initialize Swagger UI in a JavaScript project using either ES modules (`import`) or CommonJS (`require`). It targets a specific DOM element for rendering the UI.
```javascript
import SwaggerUI from 'swagger-ui'
// or use require if you prefer
// const SwaggerUI = require('swagger-ui')
SwaggerUI({
dom_id: '#myDomId'
})
```
--------------------------------
### Standalone Swagger UI Initialization (swagger-ui-dist)
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/installation.md
Illustrates initializing Swagger UI as a standalone application using `SwaggerUIBundle` from the `swagger-ui-dist` package. This method is suitable for projects that may not handle traditional NPM modules easily and requires specifying the OpenAPI URL and layout presets.
```javascript
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"
})
```
--------------------------------
### Full Swagger-UI Plugin Example
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/customization/add-plugin.md
A comprehensive example of a Swagger-UI plugin function. It showcases how to define unique action strings, utilize toolbox utilities (like Immutable.js and reselect), implement actions, wrap actions, reducers, selectors, React components, and utility functions within a single plugin.
```js
export function SomePlugin(toolbox) {
const UPDATE_SOMETHING = "some_namespace_update_something" // strings just need to be uniuqe... see below
// Tools
const fromJS = toolbox.Im.fromJS // needed below
const createSelector = toolbox.createSelector // same, needed below
return {
statePlugins: {
someNamespace: {
actions: {
actionName: (args)=> ({type: UPDATE_SOMETHING, payload: args}), // Synchronous action must return an object for the reducer to handle
anotherAction: (a,b,c) => (system) => system.someNamespaceActions.actionName(a || b) // Asynchronous actions must return a function. The function gets the whole system, and can call other actions (based on state if needed)
},
wrapActions: {
anotherAction: (oriAction, system) => (...args) => {
oriAction(...args) // Usually we at least call the original action
system.someNamespace.actionName(...args) // why not call this?
console.log("args", args) // Log the args
// anotherAction in the someNamespace has now been replaced with the this function
}
},
reducers: {
[UPDATE_SOMETHING]: (state, action) => { // Take a state (which is immutable) and an action (see synchronous actions) and return a new state
return state.set("something", fromJS(action.payload)) // we're updating the Immutable state object... we need to convert vanilla objects into an immutable type (fromJS)
// See immutable about how to modify the state
// PS: you're only working with the state under the namespace, in this case "someNamespace". So you can do what you want, without worrying about /other/ namespaces
}
},
selectors: {
// creatSelector takes a list of fn's and passes all the results to the last fn.
// eg: createSelector(a => a, a => a+1, (a,a2) => a + a2)(1) // = 3
something: createSelector( // see [reselect#createSelector](https://github.com/reactjs/reselect#createselectorinputselectors--inputselectors-resultfunc)
getState => getState(), // This is a requirement... because we `bind` selectors, we don't want to bind to any particular state (which is an immutable value) so we bind to a function, which returns the current state
state => state.get("something") // return the whatever "something" points to
),
foo: getState => "bar" // In the end selectors are just functions that we pass getState to
}
}
... // you can include as many namespaces as you want. They just get merged into the 'system'
},
components: {
foo: ()=>
Hello
// just a map of names to react components, naturally you'd want to import a fuller react component
},
fn: {
addOne: (a) => a + 1 // just any extra functions you want to include
}
}
}
```
--------------------------------
### Serve Swagger UI Assets with Express (swagger-ui-dist)
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/installation.md
Shows how to use the `swagger-ui-dist` package with an Express.js server to serve Swagger UI static assets. It utilizes the `absolutePath` helper to locate the installed module's distribution files.
```javascript
const express = require('express')
const pathToSwaggerUi = require('swagger-ui-dist').absolutePath()
const app = express()
app.use(express.static(pathToSwaggerUi))
app.listen(3000)
```
--------------------------------
### Swagger UI NPM Dependency Versioning Example
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/customization/plugin-api.md
Shows how to specify a version range for the 'swagger-ui' package in a project's 'package.json' file, using semantic versioning to manage compatibility.
```json
{
"dependencies": {
"swagger-ui": "~3.11.0"
}
}
```
--------------------------------
### Docker Environment Variable Examples
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/configuration.md
Illustrates how to set Swagger UI configuration options using environment variables in a Docker environment. These examples show common string and boolean variable assignments.
```sh
# Example for string variables
export FILTER="myFilterValue"
export LAYOUT="BaseLayout"
# Example for boolean variables (assuming they map to environment variables)
# export SHOW_MUTATED_REQUEST=true
# export PERSIST_AUTHORIZATION=true
```
--------------------------------
### React Component Example with Plugin System
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/customization/add-plugin.md
Demonstrates a React component (`Bobby`) interacting with the Swagger UI plugin system. It shows how to access actions and selectors provided by the system via `this.props` and how to dispatch actions or retrieve state using selectors.
```javascript
class Bobby extends React.Component {
handleClick(e) {
this.props.someNamespaceActions.actionName() // fires an action... which the reducer will *eventually* see
}
render() {
let { someNamespaceSelectors, someNamespaceActions } = this.props // this.props has the whole state spread
let something = someNamespaceSelectors.something() // calls our selector, which returns some state (either an immutable object or value)
return (
Hello {something}
// render the contents
)
}
}
```
--------------------------------
### Import Swagger UI Components
Source: https://github.com/swagger-api/swagger-ui/blob/master/swagger-ui-dist-package/README.md
Example of importing core Swagger UI components (`SwaggerUIBundle`, `SwaggerUIStandalonePreset`) from the `swagger-ui-dist` package using ES module syntax.
```javascript
import { SwaggerUIBundle, SwaggerUIStandalonePreset } from "swagger-ui-dist"
```
--------------------------------
### Docker: Configure Base URL and Port
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/installation.md
Demonstrates how to run the Swagger UI Docker container with custom configurations for the base URL and the application port. `BASE_URL` changes the web application's root path, and `PORT` specifies the internal port the application listens on.
```sh
docker run -p 80:80 -e BASE_URL=/swagger -e SWAGGER_JSON=/foo/swagger.json -v /bar:/foo docker.swagger.io/swaggerapi/swagger-ui
```
```sh
docker run -p 80:80 -e PORT=80 docker.swagger.io/swaggerapi/swagger-ui
```
--------------------------------
### Docker: Serve Swagger JSON from URL
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/installation.md
Executes the Swagger UI Docker container, configuring it to load the OpenAPI specification from a remote URL. The `SWAGGER_JSON_URL` environment variable is used to specify the external JSON file.
```sh
docker run -p 80:8080 -e SWAGGER_JSON_URL=https://petstore3.swagger.io/api/v3/openapi.json docker.swagger.io/swaggerapi/swagger-ui
```
--------------------------------
### Embed Swagger UI with unpkg and StandalonePreset
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/installation.md
Embeds Swagger UI using unpkg CDN links, including the StandalonePreset. This preset enables additional UI components like the TopBar and ValidatorBadge for a more complete interface.
```html
SwaggerUI
```
--------------------------------
### Configure OAuth 2.0 with initOAuth
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/oauth2.md
Example of how to initialize OAuth 2.0 configuration for Swagger UI using the `initOAuth` method after creating the SwaggerUI instance.
```javascript
const ui = SwaggerUI({
// Swagger UI configuration options
});
// 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
})
```
--------------------------------
### Docker: Serve Custom Swagger JSON from Host
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/installation.md
Runs the Swagger UI Docker container, serving a custom `swagger.json` file located on the host machine. It maps a local directory (`/bar`) to a container directory (`/foo`) and sets the `SWAGGER_JSON` environment variable to point to the file within the container.
```sh
docker run -p 80:8080 -e SWAGGER_JSON=/foo/swagger.json -v /bar:/foo docker.swagger.io/swaggerapi/swagger-ui
```
--------------------------------
### Run Swagger UI Docker Image
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/installation.md
Commands to pull and run the official Swagger UI Docker image. The first command pulls the latest image, and the second runs it, mapping port 80 on the host to port 8080 in the container.
```sh
docker pull docker.swagger.io/swaggerapi/swagger-ui
docker run -p 80:8080 docker.swagger.io/swaggerapi/swagger-ui
```
--------------------------------
### Opt out of Swagger UI Dist Analytics
Source: https://github.com/swagger-api/swagger-ui/blob/master/swagger-ui-dist-package/README.md
Configuration example for `package.json` to disable anonymized installation analytics using Scarf by setting `scarfSettings.enabled` to `false`.
```json
{
// ...
"scarfSettings": {
"enabled": false
}
// ...
}
```
--------------------------------
### Initialize Swagger UI Bundle
Source: https://github.com/swagger-api/swagger-ui/blob/master/test/e2e-cypress/static/pages/5085/index.html
Initializes the Swagger UI bundle with a specified API definition URL and configuration options. It sets up the UI layout and includes necessary presets and plugins for standalone usage. The `onComplete` callback increments a counter upon successful rendering.
```javascript
window.onload = function() {
window["SwaggerUIBundle"] = window["swagger-ui-bundle"]
window["SwaggerUIStandalonePreset"] = window["swagger-ui-standalone-preset"]
// Build a system
const ui = SwaggerUIBundle({
url: "https://petstore.swagger.io/v2/swagger.json",
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: SwaggerUIStandalonePreset ? "StandaloneLayout" : "BaseLayout",
onComplete: () => {
if(window.completeCount) {
window.completeCount++
} else {
window.completeCount = 1
}
}
})
window.ui = ui
}
```
--------------------------------
### Configure Local API Definition
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/development/setting-up.md
Modify the `url` parameter in `dev-helpers/dev-helper-initializer.js` to point to a local API definition file for development.
```javascript
url: "./examples/your-local-api-definition.yaml"
```
--------------------------------
### Initialize Swagger UI with OpenAPI/Swagger Definitions
Source: https://github.com/swagger-api/swagger-ui/blob/master/test/e2e-cypress/static/pages/multiple-urls/index.html
This script initializes the Swagger UI interface using the SwaggerUIBundle. It configures the UI to load OpenAPI and Swagger definitions from specified URLs, sets up presets and plugins for enhanced functionality, and initializes OAuth 2.0 for API authentication. It's designed to be run on page load.
```javascript
window.onload = function() {
window["SwaggerUIBundle"] = window["swagger-ui-bundle"];
window["SwaggerUIStandalonePreset"] = window["swagger-ui-standalone-preset"];
// Build a system
const ui = SwaggerUIBundle({
urls: [
{
name: "Petstore OAS",
url: "/documents/petstore-expanded.openapi.yaml"
},
{
name: "Petstore Swagger",
url: "/documents/petstore.swagger.yaml"
}
],
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout",
onComplete: () => {
if(window.completeCount) {
window.completeCount++;
} else {
window.completeCount = 1;
}
},
queryConfigEnabled: false,
});
window.ui = ui;
ui.initOAuth({
clientId: "your-client-id",
clientSecret: "your-client-secret-if-required",
realm: "your-realms",
appName: "your-app-name",
scopeSeparator: " ",
additionalQueryStringParams: {}
});
}
```
--------------------------------
### Opt-out of Anonymized Analytics
Source: https://github.com/swagger-api/swagger-ui/blob/master/flavors/swagger-ui-react/README.md
Shows how to disable anonymized analytics collection by setting a flag in package.json or via an environment variable during installation.
```json
{
// ...
"scarfSettings": {
"enabled": false
}
// ...
}
```
```bash
SCARF_ANALYTICS=false npm install
```
--------------------------------
### Deploy Swagger UI with Docker
Source: https://github.com/swagger-api/swagger-ui/wiki/For-dummies,-part-1:-installing-as-proxy-at-your-Nginx
This snippet shows the essential Docker commands to pull the Swagger UI image and run it as a container. It explains port mapping between the host and container and how to manage the running service.
```sh
docker pull swaggerapi/swagger-ui
docker run -p 80:8080 swaggerapi/swagger-ui &
docker ps
docker stop
```
--------------------------------
### Browser Console CORS Error
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/cors.md
Example of a typical browser console error message when CORS is not enabled for a requested resource.
```APIDOC
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.
```
--------------------------------
### Testing CORS with Curl
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/cors.md
Example using curl to inspect HTTP headers for CORS support, specifically checking for Access-Control-Allow-Origin and other relevant headers.
```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
```
--------------------------------
### Disable Scarf Analytics in package.json
Source: https://github.com/swagger-api/swagger-ui/blob/master/README.md
Configuration snippet for `package.json` to disable anonymized analytics collection via Scarf. This can also be achieved by setting the SCARF_ANALYTICS environment variable to false during installation.
```json
{
"scarfSettings": {
"enabled": false
}
}
```
--------------------------------
### Initialize SwaggerUI with Plugins
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/customization/add-plugin.md
Demonstrates how to initialize SwaggerUI by passing an array of plugins to the configuration object. This is the standard way to integrate custom or core plugins into the Swagger UI application.
```js
SwaggerUI({
url: 'some url',
plugins: [ ... ]
})
```
--------------------------------
### Initialize Swagger UI with API Definitions
Source: https://github.com/swagger-api/swagger-ui/blob/master/test/e2e-cypress/static/pages/5138/index.html
This JavaScript code snippet demonstrates how to initialize Swagger UI using the SwaggerUIBundle. It configures the UI to load API specifications from a remote URL or local files, sets up presets and plugins, and defines a standalone layout. The `onComplete` callback is used to track initialization status.
```javascript
window.onload = function () {
window["SwaggerUIBundle"] = window["swagger-ui-bundle"];
window["SwaggerUIStandalonePreset"] = window["swagger-ui-standalone-preset"];
// Build a system
const ui = SwaggerUIBundle({
url: "https://petstore.swagger.io/v2/swagger.json",
urls: [
{ name: "USPTO", url: "./uspto.yaml" },
{ name: "Examples", url: "./api-with-examples.yaml" },
],
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout",
onComplete: () => {
if (window.completeCount) {
window.completeCount++;
} else {
window.completeCount = 1;
}
},
queryConfigEnabled: true
});
window.ui = ui;
}
```
--------------------------------
### Get Swagger UI Asset Path
Source: https://github.com/swagger-api/swagger-ui/blob/master/swagger-ui-dist-package/README.md
Demonstrates how to use the exported `getAbsoluteFSPath` method from `swagger-ui-dist` to obtain the absolute file system path to the Swagger UI assets.
```javascript
const swaggerUiAssetPath = require("swagger-ui-dist").getAbsoluteFSPath()
// then instantiate server that serves files from the swaggerUiAssetPath
```
--------------------------------
### Configure Swagger UI Presets
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/customization/overview.md
Demonstrates how to define custom presets as arrays of plugins and pass them to the SwaggerUI constructor. Presets are compiled before other plugins.
```javascript
const MyPreset = [FirstPlugin, SecondPlugin, ThirdPlugin]
SwaggerUI({
presets: [
MyPreset
]
})
```
--------------------------------
### Get Component Reference
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/customization/overview.md
Illustrates the use of the `getComponent` helper function to retrieve references to components managed by the plugin system. It's preferred over direct imports.
```javascript
getComponent("ContainerComponentName", true)
```
--------------------------------
### Retrieving Components
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/customization/plugin-api.md
Demonstrates how to access registered components from the system using the `getComponent` method.
```javascript
// elsewhere
const HelloWorldStateless = system.getComponent("HelloWorldStateless")
const HelloWorldClass = system.getComponent("HelloWorldClass")
```
--------------------------------
### Run npm script: e2e
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/development/scripts.md
Executes end-to-end tests, which require a Java Development Kit (JDK) and Selenium to be installed. This tests the application's behavior from a user's perspective.
```shell
npm run e2e
```
--------------------------------
### Initialize Swagger UI Bundle and OAuth
Source: https://github.com/swagger-api/swagger-ui/blob/master/test/e2e-cypress/static/index.html
This snippet demonstrates how to initialize the Swagger UI bundle using JavaScript. It configures the OpenAPI specification URL, DOM element, presets, plugins, layout, and enables query configuration. It also includes the initialization of OAuth settings for authentication.
```javascript
window.onload = function() { window["SwaggerUIBundle"] = window["swagger-ui-bundle"] window["SwaggerUIStandalonePreset"] = window["swagger-ui-standalone-preset"] // Build a system const ui = SwaggerUIBundle({
url: "",
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: SwaggerUIStandalonePreset ? "StandaloneLayout" : "BaseLayout",
onComplete: () => {
if(window.completeCount) {
window.completeCount++
} else {
window.completeCount = 1
}
},
queryConfigEnabled: true,
})
window.ui = ui
ui.initOAuth({
clientId: "your-client-id",
clientSecret: "your-client-secret-if-required",
realm: "your-realms",
appName: "your-app-name",
scopeSeparator: " ",
additionalQueryStringParams: {}
})
}
```
--------------------------------
### Docker-Compose .env File Configuration
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/configuration.md
Example of setting configuration variables within a Docker Compose .env file. This syntax uses single quotes for strings and a slightly different array/object literal format.
```shell
SUPPORTED_SUBMIT_METHODS=['get', 'post']
URLS=[ { url: 'https://petstore.swagger.io/v2/swagger.json', name: 'Petstore' } ]
```
--------------------------------
### Clone Swagger UI Repository
Source: https://github.com/swagger-api/swagger-ui/wiki/For-dummies,-part-2:-rebuild-docker-image
Clones the official Swagger UI repository from GitHub to the user's home directory. This is the first step to obtain the project files for local development or modification.
```shell
cd ~\ngit clone https://github.com/swagger-api/swagger-ui.git
```
--------------------------------
### Initialize Swagger UI with Configurations
Source: https://github.com/swagger-api/swagger-ui/blob/master/test/e2e-cypress/static/pages/json-schema-2020-12-expansion/index.html
Initializes Swagger UI with a specific configuration. It defines the URL for the Swagger definition file, the DOM element to render the UI in, presets for API display, plugins for customization, and layout settings. It also configures document expansion, model display depth, and rendering style.
```javascript
window.onload = function() {
window["SwaggerUIBundle"] = window["swagger-ui-bundle"]
window["SwaggerUIStandalonePreset"] = window["swagger-ui-standalone-preset"]
// Build a system
const ui = SwaggerUIBundle({
url: "./expansion.yaml",
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [],
layout: "StandaloneLayout",
docExpansion: "full",
defaultModelExpandDepth: 100,
defaultModelRendering: "model",
onComplete: () => {
if(window.completeCount) {
window.completeCount++
} else {
window.completeCount = 1
}
},
queryConfigEnabled: true,
})
window.ui = ui
}
```
--------------------------------
### Use Swagger UI with JSON Schema Samples (JavaScript)
Source: https://github.com/swagger-api/swagger-ui/wiki/JSON-Schema-samples-API
Demonstrates how to instantiate SwaggerUI with specific plugins for JSON Schema sample generation. It shows how to access and use functions for creating samples from Draft 4/5 and Draft 2020-12 schemas.
```javascript
import SwaggerUI from 'swagger-ui';
const system = new SwaggerUI.System({
plugins: [
SwaggerUI.plugins.JSONSchema5Samples,
SwaggerUI.plugins.JSONSchema202012Samples
],
presets: [],
}).getSystem();
system.fn.jsonSchema5.getJsonSampleSchema({ type: "object", properties: { a: { type: "string" }} });
system.fn.jsonSchema202012.getJsonSampleSchema({ type: "object", properties: { a: { type: "string" }} });
```
--------------------------------
### Run npm script: dev
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/development/scripts.md
Spawns a hot-reloading development server on port 3200. This script is essential for active development cycles, providing instant feedback on code changes.
```shell
npm run dev
```
--------------------------------
### Docker: Configure IPv6 Port and Embedding
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/installation.md
Shows Docker commands to configure IPv6 listening port and control embedding behavior. `PORT_IPV6` sets the IPv6 port, and `EMBEDDING=true` enables iframe embedding by setting the appropriate HTTP headers.
```sh
docker run -p 80:80 -e PORT_IPV6=8080 docker.swagger.io/swaggerapi/swagger-ui
```
```sh
docker run -p 80:80 -e EMBEDDING=true docker.swagger.io/swaggerapi/swagger-ui
```
--------------------------------
### Basic Swagger UI Styling
Source: https://github.com/swagger-api/swagger-ui/blob/master/test/e2e-cypress/static/pages/5138/index.html
This CSS snippet provides basic styling for the Swagger UI interface, ensuring proper box-sizing and setting default margins and background for the body.
```css
html {
box-sizing: border-box;
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}
*, *:before, *:after {
box-sizing: inherit;
}
body {
margin: 0;
background: #fafafa;
}
```
--------------------------------
### Create Custom OperationsLayout for Swagger UI
Source: https://github.com/swagger-api/swagger-ui/blob/master/docs/customization/custom-layout.md
This example demonstrates creating a custom React layout component that displays only the operations section of Swagger UI. It shows how to define the layout, create a plugin to register it, and configure Swagger UI to use this custom layout.
```javascript
import React from "react"
// Create the layout component
class OperationsLayout extends React.Component {
render() {
const {
getComponent
} = this.props
const Operations = getComponent("operations", true)
return (
)
}
}
// 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"
})
```
--------------------------------
### Swagger UI Configuration Properties
Source: https://github.com/swagger-api/swagger-ui/blob/master/flavors/swagger-ui-react/README.md
Details the various properties used to configure the Swagger UI component, including their types, purposes, and important behavioral notes. Many properties are applied only once on mount.
```APIDOC
Swagger UI Configuration Properties:
requestSnippets: PropTypes.object
- Configures the request snippet core plugin.
- See Swagger UI's Display Configuration for more details.
- Note: This prop is currently only applied once, on mount. Changes to this prop's value will not be propagated to the underlying Swagger UI instance.
persistAuthorization: PropTypes.bool
- If set, it persists authorization data, preventing loss on browser close/refresh.
- Default: false.
- Note: This prop is currently only applied once, on mount. Changes to this prop's value will not be propagated to the underlying Swagger UI instance.
withCredentials: PropTypes.bool
- If set to true, enables passing credentials in CORS requests as defined in the Fetch standard.
- Note: Swagger UI cannot currently set cookies cross-domain; you will have to rely on browser-supplied cookies.
- Note: This prop is currently only applied once, on mount. Changes to this prop's value will not be propagated to the underlying Swagger UI instance.
oauth2RedirectUrl: PropTypes.string
- Redirect URL given as a parameter to the OAuth2 provider.
- Default: The URL refers to oauth2-redirect.html at the same path as Swagger UI is available.
- Note: This prop is currently only applied once, on mount. Changes to this prop's value will not be propagated to the underlying Swagger UI instance.
initialState: PropTypes.object
- Passes initial values to the Swagger UI state.
- Note: This prop is currently only applied once, on mount. Changes to this prop's value will not be propagated to the underlying Swagger UI instance.
uncaughtExceptionHandler: PropTypes.func
- Allows defining a custom uncaught exception handler.
- Default: null (uses the default handler which logs errors to the console).
- Note: This prop is currently only applied once, on mount. Changes to this prop's value will not be propagated to the underlying Swagger UI instance.
Limitations:
- Not all configuration bindings are available.
- Some props are only applied on mount and cannot be updated reliably.
- OAuth redirection handling is not supported.
- Topbar/Standalone mode is not supported.
Notes:
- The package.json in the same folder as this README is not the manifest for releases; another manifest is generated at build-time in './dist/'.
```
--------------------------------
### Increment Line Numbers Transformer
Source: https://github.com/swagger-api/swagger-ui/blob/master/src/core/plugins/err/error-transformers/README.md
An example transformer function that increments the 'line' property of each error object by 10. Transformers receive an Immutable List of Immutable Maps and are expected to return a List of similarly-formed Maps, ensuring essential keys like 'line', 'level', 'message', 'source', and 'type' are preserved.
```javascript
export function transform(errors) {
return errors.map(err => {
err.line += 10
return err
})
}
```