Swagger UI Cheat Sheet
Overview
Swagger UI is an open-source tool that dynamically generates interactive API documentation from OpenAPI (formerly Swagger) specifications. It renders your API definition as a navigable HTML interface where developers can explore endpoints, view request/response schemas, and execute live API calls directly from the browser.
Swagger UI supports OpenAPI 2.0 and OpenAPI 3.0/3.1 specifications in both JSON and YAML formats. It can be embedded in any web application, served as a standalone page, or integrated into backend frameworks through middleware packages.
Installation
Docker
# Run with your spec file
docker run -p 8080:8080 \
-e SWAGGER_JSON=/app/openapi.json \
-v $(pwd)/openapi.json:/app/openapi.json \
swaggerapi/swagger-ui
# Run with a URL to your spec
docker run -p 8080:8080 \
-e SWAGGER_JSON_URL=https://petstore.swagger.io/v2/swagger.json \
swaggerapi/swagger-ui
CDN (Quick Setup)
<!DOCTYPE html>
<html>
<head>
<title>API Documentation</title>
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js"></script>
<script>
SwaggerUIBundle({
url: "/openapi.json",
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset
],
layout: "StandaloneLayout"
});
</script>
</body>
</html>
npm
npm install swagger-ui-dist
# Or for React projects
npm install swagger-ui-react
Configuration Options
const ui = SwaggerUIBundle({
url: "https://api.example.com/openapi.json",
dom_id: '#swagger-ui',
layout: "StandaloneLayout",
deepLinking: true,
displayOperationId: false,
displayRequestDuration: true,
defaultModelsExpandDepth: 1,
docExpansion: "list",
filter: true,
showExtensions: true,
tryItOutEnabled: false,
operationsSorter: "alpha",
tagsSorter: "alpha",
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset,
],
requestInterceptor: (req) => {
req.headers['X-Custom-Header'] = 'value';
return req;
},
responseInterceptor: (res) => {
console.log('Response:', res.status);
return res;
},
});
Docker Environment Variables
| Variable | Description |
|---|---|
SWAGGER_JSON | Path to spec file inside container |
SWAGGER_JSON_URL | URL to fetch spec from |
BASE_URL | Base path for Swagger UI (default: /) |
PORT | Port to serve on (default: 8080) |
OpenAPI Specification Basics
openapi: 3.0.3
info:
title: My API
description: API description here
version: 1.0.0
servers:
- url: https://api.example.com/v1
description: Production
- url: https://staging-api.example.com/v1
description: Staging
paths:
/users:
get:
summary: List all users
operationId: listUsers
tags:
- Users
parameters:
- name: limit
in: query
schema:
type: integer
default: 20
responses:
'200':
description: Successful response
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
post:
summary: Create a user
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CreateUser'
responses:
'201':
description: User created
components:
schemas:
User:
type: object
properties:
id:
type: string
format: uuid
name:
type: string
email:
type: string
format: email
securitySchemes:
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
security:
- BearerAuth: []
Framework Integration
Express.js
npm install swagger-ui-express
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const spec = require('./openapi.json');
const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(spec, {
customSiteTitle: "My API Docs",
customCss: '.swagger-ui .topbar { display: none }',
swaggerOptions: {
persistAuthorization: true,
displayRequestDuration: true,
},
}));
app.listen(3000);
FastAPI (Python)
from fastapi import FastAPI
app = FastAPI(
title="My API",
description="API description",
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc",
openapi_url="/openapi.json",
)
Spring Boot (Java)
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.3.0</version>
</dependency>
React Integration
import SwaggerUI from "swagger-ui-react";
import "swagger-ui-react/swagger-ui.css";
function ApiDocs() {
return (
<SwaggerUI
url="/openapi.json"
docExpansion="list"
displayRequestDuration={true}
/>
);
}
Advanced Usage
Custom Authentication
const ui = SwaggerUIBundle({
url: "/openapi.json",
dom_id: '#swagger-ui',
requestInterceptor: (request) => {
const token = localStorage.getItem('access_token');
if (token) {
request.headers['Authorization'] = 'Bearer ' + token;
}
return request;
},
persistAuthorization: true,
});
Custom CSS
.swagger-ui .topbar { display: none; }
.swagger-ui .opblock.opblock-get {
border-color: #61affe;
background: rgba(97, 175, 254, 0.1);
}
.swagger-ui .opblock.opblock-post {
border-color: #49cc90;
background: rgba(73, 204, 144, 0.1);
}
Troubleshooting
| Issue | Solution |
|---|---|
| CORS errors on Try It Out | Configure CORS on your API server |
| Spec not loading | Check URL accessibility; verify JSON/YAML validity |
| Authentication not persisting | Enable persistAuthorization: true in config |
| Models not displaying | Check defaultModelsExpandDepth setting |
| Slow rendering with large spec | Split spec into multiple files; use $ref |
| Validator errors | Validate spec at editor.swagger.io |
| Try It Out returns wrong URL | Verify servers in spec |
| Custom CSS not applying | Load CSS after swagger-ui.css |