Swagger UI

GitHub Overview

swagger-api/swagger-ui

Swagger UI is a collection of HTML, JavaScript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API.

Stars28,026
Watchers643
Forks9,179
Created:July 15, 2011
Language:JavaScript
License:Apache License 2.0

Topics

hacktoberfestoasopen-sourceopenapiopenapi-specificationopenapi3openapi31restrest-apiswaggerswagger-apiswagger-jsswagger-ossswagger-ui

Star History

swagger-api/swagger-ui Star History
Data as of: 8/13/2025, 01:43 AM

Development Tool

Swagger UI

Overview

Swagger UI is an interactive API documentation tool automatically generated from OpenAPI specifications. As an industry-standard API documentation tool, it allows development teams and users to visualize and interact with API resources without any implementation logic. With the proliferation of API-First development methodology, it has become an essential tool in modern API development.

Details

Swagger UI is a web-based tool that dynamically generates API documentation based on OpenAPI (formerly Swagger) specifications. Provided as a collection of HTML, JavaScript, and CSS assets, it automatically constructs beautiful and functional documentation from OpenAPI definitions. Its greatest feature is providing an interactive environment where documentation is not just information display, but actually allows calling API endpoints. Developers can understand and verify API functionality without implementation code or network traffic investigation. The OpenAPI specification defines a standard interface for RESTful APIs, allowing both humans and computers to understand service capabilities without direct access to source code or documentation. As part of the Swagger ecosystem provided by SmartBear, it integrates with Swagger Codegen (server/client code generation), Swagger Editor (browser-based editor), and Swagger Core (Java-related libraries) to form a comprehensive API development and management platform. Operating solely on web standard technologies, it provides platform independence while enabling real-time API exploration and testing.

Advantages & Disadvantages

Advantages

  • Standard Specification Compliance: Widely adopted as industry standard for OpenAPI specifications
  • Interactive Operation: Ability to directly execute and verify APIs within documentation
  • Automatic Generation: Automatically constructs beautiful documentation from OpenAPI definitions
  • Platform Independent: Accessible anywhere with a web browser
  • Developer & User Support: Supports both backend implementation and client usage
  • Swagger Ecosystem: Complete integration with Codegen, Editor, and other tools
  • Customizable: Supports theme and layout customization
  • Free & Open Source: Freely available under Apache 2.0 license

Disadvantages

  • OpenAPI Dependency: Completely dependent on OpenAPI specification quality
  • Limited Dynamic Features: Static generation limits advanced interaction capabilities
  • Authentication Complexity: Difficult to express and test complex authentication flows
  • Performance: Can become slow with large-scale APIs for display and operations
  • Version Management: Challenges in managing documentation updates with API specification changes

Reference Links

Usage Examples

Basic OpenAPI Specification (swagger.yaml)

openapi: 3.0.0
info:
  title: User Management API
  description: API specification for user management system
  version: 1.0.0
  contact:
    name: API Support
    email: [email protected]
servers:
  - url: https://api.example.com/v1
    description: Production environment
  - url: https://api-staging.example.com/v1
    description: Staging environment

paths:
  /users:
    get:
      summary: Get user list
      description: Retrieve a list of users registered in the system
      parameters:
        - name: page
          in: query
          description: Page number
          required: false
          schema:
            type: integer
            default: 1
        - name: limit
          in: query
          description: Number of items per page
          required: false
          schema:
            type: integer
            default: 10
            maximum: 100
      responses:
        '200':
          description: Successfully retrieved user list
          content:
            application/json:
              schema:
                type: object
                properties:
                  users:
                    type: array
                    items:
                      $ref: '#/components/schemas/User'
                  pagination:
                    $ref: '#/components/schemas/Pagination'
        '400':
          description: Invalid request parameters
        '500':
          description: Internal server error

    post:
      summary: Create user
      description: Create a new user
      security:
        - ApiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateUserRequest'
      responses:
        '201':
          description: User created successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '400':
          description: Validation error
        '401':
          description: Authentication required
        '409':
          description: User already exists

  /users/{userId}:
    get:
      summary: Get user details
      description: Retrieve information for a user with the specified ID
      parameters:
        - name: userId
          in: path
          required: true
          description: User ID
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Successfully retrieved user details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '404':
          description: User not found

    put:
      summary: Update user
      description: Update information for a user with the specified ID
      security:
        - ApiKeyAuth: []
      parameters:
        - name: userId
          in: path
          required: true
          schema:
            type: string
            format: uuid
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateUserRequest'
      responses:
        '200':
          description: User updated successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '400':
          description: Validation error
        '401':
          description: Authentication required
        '404':
          description: User not found

    delete:
      summary: Delete user
      description: Delete a user with the specified ID
      security:
        - ApiKeyAuth: []
      parameters:
        - name: userId
          in: path
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '204':
          description: User deleted successfully
        '401':
          description: Authentication required
        '404':
          description: User not found

components:
  schemas:
    User:
      type: object
      required:
        - id
        - name
        - email
      properties:
        id:
          type: string
          format: uuid
          description: User ID
          example: "123e4567-e89b-12d3-a456-426614174000"
        name:
          type: string
          description: User name
          example: "John Doe"
        email:
          type: string
          format: email
          description: Email address
          example: "[email protected]"
        age:
          type: integer
          minimum: 0
          maximum: 120
          description: Age
          example: 30
        created_at:
          type: string
          format: date-time
          description: Creation timestamp
          example: "2025-01-15T10:30:00Z"
        updated_at:
          type: string
          format: date-time
          description: Update timestamp
          example: "2025-01-15T14:45:00Z"

    CreateUserRequest:
      type: object
      required:
        - name
        - email
      properties:
        name:
          type: string
          description: User name
          example: "John Doe"
        email:
          type: string
          format: email
          description: Email address
          example: "[email protected]"
        age:
          type: integer
          minimum: 0
          maximum: 120
          description: Age
          example: 30

    UpdateUserRequest:
      type: object
      properties:
        name:
          type: string
          description: User name
          example: "Jane Doe"
        email:
          type: string
          format: email
          description: Email address
          example: "[email protected]"
        age:
          type: integer
          minimum: 0
          maximum: 120
          description: Age
          example: 32

    Pagination:
      type: object
      properties:
        page:
          type: integer
          description: Current page number
          example: 1
        limit:
          type: integer
          description: Number of items per page
          example: 10
        total:
          type: integer
          description: Total number of items
          example: 150
        total_pages:
          type: integer
          description: Total number of pages
          example: 15

  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key
      description: API key authentication
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: JWT token authentication

security:
  - ApiKeyAuth: []
  - BearerAuth: []

HTML Integration with Swagger UI

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Management API Documentation</title>
    <link rel="stylesheet" type="text/css" href="https://unpkg.com/[email protected]/swagger-ui.css" />
    <style>
        html {
            box-sizing: border-box;
            overflow: -moz-scrollbars-vertical;
            overflow-y: scroll;
        }
        *, *:before, *:after {
            box-sizing: inherit;
        }
        body {
            margin:0;
            background: #fafafa;
        }
    </style>
</head>
<body>
    <div id="swagger-ui"></div>
    
    <script src="https://unpkg.com/[email protected]/swagger-ui-bundle.js"></script>
    <script src="https://unpkg.com/[email protected]/swagger-ui-standalone-preset.js"></script>
    <script>
        window.onload = function() {
            // Begin Swagger UI call region
            const ui = SwaggerUIBundle({
                url: './swagger.yaml',
                dom_id: '#swagger-ui',
                deepLinking: true,
                presets: [
                    SwaggerUIBundle.presets.apis,
                    SwaggerUIStandalonePreset
                ],
                plugins: [
                    SwaggerUIBundle.plugins.DownloadUrl
                ],
                layout: "StandaloneLayout",
                tryItOutEnabled: true,
                requestInterceptor: function(request) {
                    // Auto-add API key
                    request.headers['X-API-Key'] = 'your-api-key-here';
                    return request;
                },
                responseInterceptor: function(response) {
                    // Response logging
                    console.log('API Response:', response);
                    return response;
                }
            });
            // End Swagger UI call region
        };
    </script>
</body>
</html>

Node.js Express Integration Example

// package.json dependencies:
// "express": "^4.18.0",
// "swagger-ui-express": "^4.6.0",
// "yamljs": "^0.3.0"

const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const path = require('path');

const app = express();

// Load OpenAPI specification
const swaggerDocument = YAML.load(path.join(__dirname, 'swagger.yaml'));

// Custom CSS
const customCss = "\\n" + 
  "  .topbar-wrapper { display: none; }\\n" +
  "  .swagger-ui .topbar { background-color: #2c3e50; }\\n" +
  "  .swagger-ui .info .title { color: #2c3e50; }\\n";

// Swagger UI options
const swaggerOptions = {
  explorer: true,
  customCss: customCss,
  customSiteTitle: "User Management API",
  swaggerOptions: {
    persistAuthorization: true,
    tryItOutEnabled: true,
    filter: true,
    displayRequestDuration: true
  }
};

// Setup Swagger UI
app.use('/api-docs', swaggerUi.serve);
app.get('/api-docs', swaggerUi.setup(swaggerDocument, swaggerOptions));

// Root endpoint
app.get('/', (req, res) => {
  res.redirect('/api-docs');
});

// API endpoints (implementation example)
app.use(express.json());

app.get('/v1/users', (req, res) => {
  const { page = 1, limit = 10 } = req.query;
  
  // Mock data
  const users = [
    {
      id: "123e4567-e89b-12d3-a456-426614174000",
      name: "John Doe",
      email: "[email protected]",
      age: 30,
      created_at: "2025-01-15T10:30:00Z",
      updated_at: "2025-01-15T14:45:00Z"
    }
  ];
  
  res.json({
    users: users,
    pagination: {
      page: parseInt(page),
      limit: parseInt(limit),
      total: 150,
      total_pages: Math.ceil(150 / limit)
    }
  });
});

app.post('/v1/users', (req, res) => {
  const { name, email, age } = req.body;
  
  // Validation
  if (!name || !email) {
    return res.status(400).json({ error: 'Name and email are required' });
  }
  
  // Mock response
  const newUser = {
    id: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
    name,
    email,
    age,
    created_at: new Date().toISOString(),
    updated_at: new Date().toISOString()
  };
  
  res.status(201).json(newUser);
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log(`API Documentation: http://localhost:${PORT}/api-docs`);
});

Docker Integration and Deployment

# Dockerfile
FROM node:18-alpine

WORKDIR /app

# Install dependencies
COPY package*.json ./
RUN npm ci --only=production

# Copy application files
COPY . .

EXPOSE 3000

CMD ["npm", "start"]
# docker-compose.yml
version: '3.8'
services:
  api-docs:
    build: .
    ports:
      - "3000:3000"
    environment:
      - NODE_ENV=production
    volumes:
      - ./swagger.yaml:/app/swagger.yaml:ro
    restart: unless-stopped

  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
    depends_on:
      - api-docs
    restart: unless-stopped

CI/CD Integration and API Specification Validation

# .github/workflows/api-docs.yml
name: API Documentation

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  validate-openapi:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    
    - name: Validate OpenAPI Spec
      uses: char0n/swagger-editor-validate@v1
      with:
        definition-file: swagger.yaml
    
    - name: Generate API Documentation
      run: |
        npm install -g swagger-ui-dist
        swagger-ui-dist-cli -f swagger.yaml -d api-docs/
    
    - name: Deploy to GitHub Pages
      if: github.ref == 'refs/heads/main'
      uses: peaceiris/actions-gh-pages@v3
      with:
        github_token: ${{ secrets.GITHUB_TOKEN }}
        publish_dir: ./api-docs