Skip to main content

Swagger UI for Python web framework, such as Tornado, Flask, Quart, Sanic and Falcon.

Project description

tests Version

Documentation

swagger-ui-python

Seamless Swagger UI integration for Python web frameworks. A unified, framework-agnostic API for adding interactive OpenAPI documentation to your Python applications with automatic framework detection.

Note: This is a maintained fork of PWZER/swagger-ui-py.

Status: Production-ready, actively maintained Python: 3.9, 3.10, 3.11, 3.12 Swagger UI: v5.25.3 Swagger Editor: v4.14.6

Key Features

  • Framework Agnostic - Single API works across 9+ Python frameworks
  • Auto-Detection - Automatically detects your framework, zero configuration needed
  • Multiple Config Sources - YAML/JSON files, remote URLs, Python dicts, or strings
  • Swagger Editor - Optional inline spec editor for live documentation editing
  • Static Assets - Automatic CSS, JS, images, and icons serving
  • Customization - Custom CSS, Swagger UI parameters, OAuth2 configuration
  • Well-Tested - 50+ test cases across all supported frameworks

Supported Frameworks

Check supported frameworks:

python3 -c "from swagger_ui import supported_list; print(supported_list)"
# Output: ['flask', 'tornado', 'sanic', 'aiohttp', 'quart', 'starlette', 'falcon', 'bottle', 'chalice']

Quick Start

Installation

pip install swagger-ui-python

Basic Example (Flask)

from flask import Flask
from swagger_ui import api_doc

app = Flask(__name__)

# Auto-detects Flask and registers routes
api_doc(app, config_path='./openapi.yaml')

if __name__ == '__main__':
    app.run(debug=True)
    # Visit: http://localhost:5000/api/doc

Basic Example (Tornado)

import tornado.ioloop
from tornado.web import Application
from swagger_ui import api_doc

app = Application()

# Auto-detects Tornado and registers routes
api_doc(app, config_path='./openapi.yaml', url_prefix='/api/doc')

if __name__ == '__main__':
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()
    # Visit: http://localhost:8888/api/doc

Configuration Options

1. Configuration Sources (in priority order)

Option A: YAML/JSON File

api_doc(app, config_path='./openapi.yaml')

Option B: Remote URL (requires CORS)

api_doc(app, config_url='https://petstore.swagger.io/v2/swagger.json')

Option C: Python Dict

config = {
    "openapi": "3.0.1",
    "info": {"title": "My API", "version": "1.0.0"},
    "paths": { ... }
}
api_doc(app, config=config)

Option D: JSON/YAML String

spec_string = '{"openapi":"3.0.1","info":{"title":"My API"},...}'
api_doc(app, config_spec=spec_string)

Option E: External Endpoint

api_doc(app, config_rel_url='/swagger.json')  # App provides endpoint

2. Common Parameters

api_doc(
    app,
    config_path='./openapi.yaml',      # Config source
    url_prefix='/api/doc',              # Internal route path (default: '/api/doc')
    base_url=None,                      # External URL for assets (defaults to url_prefix)
    title='API Documentation',          # HTML page title
    editor=False,                       # Enable spec editor
    custom_css='https://cdn.../style.css',  # Custom CSS
    host_inject=True,                   # Auto-inject request host
)

3. Reverse Proxy Support

When running behind a reverse proxy with a path prefix (e.g., ingress /service/* → backend), use base_url to set the external URL path for static assets:

# Proxy routes /service/docs/* to backend /docs/*
api_doc(
    app,
    config_path='./openapi.yaml',
    url_prefix='/docs',              # Internal routes registered at /docs
    base_url='/service/docs',        # Assets linked as /service/docs/static/*
)
  • url_prefix - Used for internal route registration (app-side)
  • base_url - Used for asset URLs in HTML templates (browser-side, defaults to url_prefix)

4. Swagger UI Customization

parameters = {
    "deepLinking": "true",
    "displayRequestDuration": "true",
    "layout": "\"StandaloneLayout\"",
    "plugins": "[SwaggerUIBundle.plugins.DownloadUrl]",
}
api_doc(app, config_path='./openapi.yaml', parameters=parameters)

See Swagger UI Parameters for all options.

5. OAuth2 Configuration

oauth2_config = {
    "clientId": "\"your-client-id\"",
    "clientSecret": "\"your-secret\"",
    "realm": "\"your-realm\"",
    "appName": "\"your-app\"",
    "scopeSeparator": "\" \"",
    "scopes": "\"openid profile\"",
}
api_doc(app, config_path='./openapi.yaml', oauth2_config=oauth2_config)

See OAuth2 Configuration for details.

6. Legacy Framework-Specific APIs

Still supported for backward compatibility:

from swagger_ui import flask_api_doc, tornado_api_doc, sanic_api_doc

# Same as api_doc(app, ...) but explicit
flask_api_doc(app, config_path='./openapi.yaml')
tornado_api_doc(app, config_path='./openapi.yaml')
sanic_api_doc(app, config_path='./openapi.yaml')

Routes Created

The library automatically creates these routes (at url_prefix=/api/doc):

  • GET /api/doc - Interactive Swagger UI documentation
  • GET /api/doc/swagger.json - OpenAPI specification (JSON)
  • GET /api/doc/editor - Swagger Editor (if editor=True)
  • GET /api/doc/static/{path} - Static assets (CSS, JS, images)

Creating OpenAPI Specifications

For details on writing OpenAPI specifications:

Versions

  • Swagger UI: v5.25.3 (GitHub)
  • Swagger Editor: v4.14.6 (GitHub)

To update to newer versions:

tox -e update
# or
python tools/update.py --ui-version=v5.25.3 --editor-version=v4.14.6

Extending the Library

Adding Support for New Frameworks

To add support for a new framework:

  1. Create swagger_ui/handlers/{framework}.py following the handler interface
  2. Implement handler(doc) and match(doc) functions
  3. Add tests in test/{framework}_test.py
  4. Update README with framework name
  5. Auto-discovery will handle the rest

See Code Standards for detailed guidelines.

Custom Parameters & Configuration

Pass custom parameters and OAuth2 configuration through the api_doc() function for full control over Swagger UI behavior.

Documentation

Full documentation available in the ./docs directory:

Development

Setup

# Clone repository
git clone https://github.com/SkyTik/swagger-ui-python.git
cd swagger-ui-python

# Install dev dependencies
pip install -e ".[dev]"

# Run tests
make pytest

# Format code
make format

# Build wheel
make whl

Testing

make pytest              # Run all tests
make format-check        # Check code style
make format              # Auto-format code

Building & Release

make whl                 # Build wheel
make upload              # Upload to PyPI

Troubleshooting

Framework not detected:

  • Ensure framework is installed
  • Try explicit app_type parameter: api_doc(app, app_type='flask', ...)

Config not loading:

  • Check file path exists and is readable
  • Validate YAML/JSON format using Swagger Editor
  • Check CORS headers if using remote URL

Routes not registered:

  • Ensure api_doc() called before app starts
  • Check url_prefix doesn't conflict with existing routes
  • Verify framework-specific setup (e.g., app.register_blueprint() for Flask)

For more help:

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Ensure tests pass: make pytest
  5. Format code: make format
  6. Submit a pull request

See Code Standards for contribution guidelines.

License

Licensed under the Apache License 2.0. See LICENSE file for details.

Support

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

swagger_ui_python-1.0.3.tar.gz (7.0 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

swagger_ui_python-1.0.3-py3-none-any.whl (7.0 MB view details)

Uploaded Python 3

File details

Details for the file swagger_ui_python-1.0.3.tar.gz.

File metadata

  • Download URL: swagger_ui_python-1.0.3.tar.gz
  • Upload date:
  • Size: 7.0 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for swagger_ui_python-1.0.3.tar.gz
Algorithm Hash digest
SHA256 4b03a2e5a277d364cb8a590b0d37f4f509ce999768f83e786d3e6f56a7b77403
MD5 70c946746f23e4d7c72c6a7654cff0ba
BLAKE2b-256 f7682e2297e883d97a6e375f89c2a946e6341822b9929016fa9dd45f14046ef5

See more details on using hashes here.

Provenance

The following attestation bundles were made for swagger_ui_python-1.0.3.tar.gz:

Publisher: release.yml on SkyTik/swagger-ui-py

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file swagger_ui_python-1.0.3-py3-none-any.whl.

File metadata

File hashes

Hashes for swagger_ui_python-1.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 acdbcf941edccc3fc3084c13febd48fe74de4601ce808fc1dc7c0316d772f8fc
MD5 faebc64104baeebb7524d490c866d4a4
BLAKE2b-256 7b59b2d9aa328ed2e8f2211bf9fb948c67d44277ef18b314fb1b582e4a20636c

See more details on using hashes here.

Provenance

The following attestation bundles were made for swagger_ui_python-1.0.3-py3-none-any.whl:

Publisher: release.yml on SkyTik/swagger-ui-py

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page