Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
dantetemplar committed Aug 12, 2024
0 parents commit 19360df
Show file tree
Hide file tree
Showing 16 changed files with 952 additions and 0 deletions.
31 changes: 31 additions & 0 deletions .github/workflows/listen-swagger-changes.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
name: "Check for new Swagger release 🕵️‍♂️"
on:
schedule:
- cron: "0 0 * * *" # Every day at midnight

jobs:
check:
runs-on: ubuntu-latest
steps:
- name: "Check out repository 🚚"
uses: actions/checkout@v4
- name: "Set up Python 🐍"
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: "Install python libraries 📚"
run: python -m pip install requests
- name: "Check for new Swagger release 🕵️‍♂️"
run: python check_swagger.py
# It will set SWAGGER_UI_UPDATED and SWAGGER_UI_VERSION env variables
# If there is a new release, then needed files will be updated
- name: "Make a commit if needed 📝"
run: |
if [ "$SWAGGER_UI_UPDATED" = "true" ]; then
git config --global user.email "[email protected]"
git config --global user.name "Automated Swagger UI update"
git add 'fastapi_swagger/resources'
git add 'latest_release.txt`
git commit -m "chore: update Swagger UI to $SWAGGER_UI_VERSION"
git push
fi
Empty file added .github/workflows/release.yaml
Empty file.
14 changes: 14 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
### Build ###
dist

### IDE and OS ###
.idea
.vscode
.DS_Store

### Cache ###
__pycache__
*.py[cod]

### Virtual Environment ###
venv
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Ruslan Bel'kov

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
80 changes: 80 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# FastAPI Swagger Plugin

This plugin updates the FastAPI app to include a latest Swagger UI distribution. Also, it works locally and does not
depend on the @tiangolo domains and cdns.

## Why?

The FastAPI already includes a Swagger UI. However, author updates swagger not so often. Moreover he uses his own
hosts for the resources, and they are not always available (especially in Russia). This plugin allows to use the latest
Swagger UI distribution and host it inside your app.

## Usage

### Installation

```bash
pip install fastapi_swagger
```

### Basic Usage

```python
from fastapi import FastAPI
from fastapi_swagger import patch_fastapi

app = FastAPI(docs_url=None, swagger_ui_oauth2_redirect_url=None) # docs url will be at /docs

patch_fastapi(app)
```

## How it works?

How it was before:
FastAPI uses the `get_swagger_ui_html` function to render the Swagger UI under the hood.

```python
def get_swagger_ui_html(
*,
openapi_url: str,
title: str,
swagger_js_url: str = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js",
swagger_css_url: str = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css",
swagger_favicon_url: str = "https://fastapi.tiangolo.com/img/favicon.png",
oauth2_redirect_url: Optional[str] = None,
init_oauth: Optional[Dict[str, Any]] = None,
swagger_ui_parameters: Optional[Dict[str, Any]] = None,
) -> HTMLResponse:
...
```

How it is now:

Actually, we just copy the Swagger UI distribution from
the [GitHub releases](https://github.com/swagger-api/swagger-ui/releases) to the `fastapi_swagger` package, and serve it
from your app.
Patch creates several additional routes with the Swagger UI resources and one route for docs page (btw, using same
`get_swagger_ui_html` function).

```python
def patch_fastapi(
app: FastAPI,
docs_url: str = "/docs",
*,
title: Optional[str],
swagger_js_url: str = "/swagger/swagger-ui-bundle.js", # relative path from app root
swagger_css_url: str = "/swagger/swagger-ui.css", # relative path from app root
swagger_favicon_url: str = "/swagger/favicon-32x32.png", # relative path from app root
oauth2_redirect_url: Optional[str] = None,
init_oauth: Optional[Dict[str, Any]] = None,
swagger_ui_parameters: Optional[Dict[str, Any]] = None,
):
...


patch_fastapi(app)
# Now there are additional routes /swagger/swagger-ui-bundle.js, /swagger/swagger-ui.css, /swagger/favicon-32x32.png and /docs
# They all are not dependent on the external resources.
```

```python
3 changes: 3 additions & 0 deletions fastapi_swagger/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
__all__ = ["patch_fastapi"]

from .main import patch_fastapi
88 changes: 88 additions & 0 deletions fastapi_swagger/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
from importlib import resources
from typing import Optional, Dict, Any

from fastapi import FastAPI, Response, Request
from fastapi.openapi.docs import get_swagger_ui_html
from starlette.responses import RedirectResponse


def patch_fastapi(
app: FastAPI,
docs_url: str = "/docs",
redirect_from_root_to_docs: bool = True,
*,
title: Optional[str],
swagger_js_url: str = "/swagger/swagger-ui-bundle.js", # relative path from app root
swagger_css_url: str = "/swagger/swagger-ui.css", # relative path from app root
swagger_favicon_url: str = "/swagger/favicon-32x32.png", # relative path from app root
oauth2_redirect_url: Optional[str] = None,
init_oauth: Optional[Dict[str, Any]] = None,
swagger_ui_parameters: Optional[Dict[str, Any]] = None,
):
"""
Patch FastAPI app to serve Swagger UI using fastapi_swagger plugin
:param app: FastAPI app
:param docs_url: URL to serve Swagger UI
:param redirect_from_root_to_docs: Redirect from root to Swagger UI (default: True)
:param title: Title of Swagger UI page (default: f"{app.title} - Swagger UI") - html title
:param swagger_js_url: Where to serve Swagger UI JS bundle
:param swagger_css_url: Where to serve Swagger UI CSS
:param swagger_favicon_url: Where to serve Swagger UI favicon image - html icon
:param swagger_ui_parameters: Parameters for Swagger UI
(default: {"tryItOutEnabled": True, "persistAuthorization": True, "filter": True})
:param init_oauth: OAuth2 configuration
:param oauth2_redirect_url: OAuth2 redirect URL
"""
if redirect_from_root_to_docs:

@app.get("/", include_in_schema=False)
async def redirect_to_docs(request: Request):
return RedirectResponse(url=request.url_for("swagger_ui_html"))

@app.get(docs_url, tags=["Swagger"], include_in_schema=False)
async def swagger_ui_html(request: Request):
nonlocal swagger_ui_parameters, title, oauth2_redirect_url
root_path = request.scope.get("root_path", "").rstrip("/")
openapi_url = root_path + app.openapi_url
_swagger_js_url = request.url_for("swagger_ui_bundle_js")
_swagger_css_url = request.url_for("swagger_ui_css")
_swagger_favicon_url = request.url_for("swagger_favicon_png")
if swagger_ui_parameters is None:
swagger_ui_parameters = {
"tryItOutEnabled": True,
"persistAuthorization": True,
"filter": True,
}
return get_swagger_ui_html(
openapi_url=openapi_url,
title=title or f"{app.title} - Swagger UI",
swagger_js_url=str(_swagger_js_url),
swagger_css_url=str(_swagger_css_url),
swagger_favicon_url=str(_swagger_favicon_url),
oauth2_redirect_url=oauth2_redirect_url,
init_oauth=init_oauth,
swagger_ui_parameters=swagger_ui_parameters,
)

@app.get(swagger_js_url, tags=["Swagger"], include_in_schema=False)
async def swagger_ui_bundle_js() -> Response:
with resources.open_binary(
"fastapi_swagger.resources", "swagger-ui-bundle.js"
) as f:
_ = f.read()
return Response(content=_, media_type="application/javascript")

@app.get(swagger_css_url, tags=["Swagger"], include_in_schema=False)
async def swagger_ui_css() -> Response:
with resources.open_binary("fastapi_swagger.resources", "swagger-ui.css") as f:
_ = f.read()
return Response(content=_, media_type="text/css")

@app.get(swagger_favicon_url, tags=["Swagger"], include_in_schema=False)
async def swagger_favicon_png() -> Response:
with resources.open_binary(
"fastapi_swagger.resources", "favicon-32x32.png"
) as f:
_ = f.read()
return Response(content=_, media_type="image/png")
Empty file.
Binary file added fastapi_swagger/resources/favicon-32x32.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 2 additions & 0 deletions fastapi_swagger/resources/swagger-ui-bundle.js

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions fastapi_swagger/resources/swagger-ui.css

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions latest_release.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v5.17.14
107 changes: 107 additions & 0 deletions listen_swagger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import io
import os
import shutil
import tarfile
from pathlib import Path

import requests

# Set the GitHub API URL for Swagger UI releases
GITHUB_API_URL = "https://api.github.com/repos/swagger-api/swagger-ui/releases/latest"

# Define where to store the downloaded files
DOWNLOAD_DIR = Path("fastapi_swagger/resources")

# File to store the latest release tag
LATEST_RELEASE_FILE = "latest_release.txt"


def get_latest_release():
response = requests.get(GITHUB_API_URL)
if response.status_code == 200:
release_data = response.json()
return release_data["tag_name"], release_data["tarball_url"]
else:
raise Exception("Failed to fetch release data from GitHub.")


def download_assets(tarball_url):
if not os.path.exists(DOWNLOAD_DIR):
os.makedirs(DOWNLOAD_DIR)
else:
shutil.rmtree(DOWNLOAD_DIR)
os.makedirs(DOWNLOAD_DIR)

response = requests.get(tarball_url, stream=True)
if response.status_code == 200:
with io.BytesIO(response.content) as f:
tar = tarfile.open(fileobj=f)
filtered = []
for m in tar.getmembers():
as_path = Path(m.path)
if (
as_path.parent
and as_path.parent.name == "dist"
and as_path.name
in ("favicon-32x32.png", "swagger-ui.css", "swagger-ui-bundle.js")
):
filtered.append(m)
tar.extractall(DOWNLOAD_DIR, members=filtered)
# Now it like
# swagger-ui
# ├── swagger-apr-swagger-ui-*
# │ ├── dist
# │ │ ├── favicon-32x32.png
# │ │ ├── swagger-ui.css
# │ │ └── swagger-ui-bundle.js

# Need to be
# swagger-ui
# ├── favicon-32x32.png
# ├── swagger-ui.css
# ├── swagger-ui-bundle.js
# ├── __init__.py

# Move the files to the root of the DOWNLOAD_DIR
for f in DOWNLOAD_DIR.rglob("*"):
if f.is_file():
shutil.move(f, DOWNLOAD_DIR)
# Remove the extracted directory
for d in DOWNLOAD_DIR.rglob("swagger-api-swagger-ui-*"):
shutil.rmtree(d)
# Add __init__.py
Path(DOWNLOAD_DIR / "__init__.py").touch()
else:
raise Exception("Failed to download assets from GitHub.")


def check_and_download_new_release():
latest_release, tarball_url = get_latest_release()
print(f"Latest release: {latest_release}")

if os.path.exists(LATEST_RELEASE_FILE):
with open(LATEST_RELEASE_FILE, "r") as f:
stored_release = f.read().strip()
else:
stored_release = None

if latest_release != stored_release:
print("New release detected. Downloading assets...")
download_assets(tarball_url)
with open(LATEST_RELEASE_FILE, "w") as f:
f.write(latest_release)
print("Assets downloaded and release version updated.")
return True, latest_release
else:
print("No new release detected.")
return False, stored_release


if __name__ == "__main__":
updated, version = check_and_download_new_release()
env_file = os.getenv("GITHUB_ENV")
if env_file:
with open(env_file, "a") as myfile:
myfile.write("SWAGGER_UI_VERSION=" + version + "\n")
updated_ = "true" if updated else "false"
myfile.write("SWAGGER_UI_UPDATED=" + updated_ + "\n")
Loading

0 comments on commit 19360df

Please sign in to comment.