Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 43 additions & 2 deletions src/labthings_fastapi/server/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@
from anyio.from_thread import BlockingPortal
from fastapi import APIRouter, FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.openapi.docs import (
get_swagger_ui_html,
get_swagger_ui_oauth2_redirect_html,
)
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.testclient import TestClient
from pydantic import ValidationError
from pydantic_core import PydanticSerializationError
Expand Down Expand Up @@ -145,7 +149,12 @@ def __init__(
self._config = ThingServerConfig(**kwargs)
if self._config.settings_folder is None:
self._config.settings_folder = "./settings"
self.app = FastAPI(lifespan=self.lifespan, separate_input_output_schemas=False)
# docs_url=None prevents the default docs page so labthings-fastapi
# can customise its own
self.app = FastAPI(
lifespan=self.lifespan, separate_input_output_schemas=False, docs_url=None
)
self._add_swagger_ui()
self._set_cors_middleware()
self._set_url_for_middleware()
self._add_exception_handlers()
Expand All @@ -163,6 +172,38 @@ def __init__(
self._connect_things()
self._attach_things_to_server()

def _add_swagger_ui(self) -> None:
"""Replace FastAPI's default Swagger UI with a pinned version.

:raises ValueError: If the OpenAPI or OAuth2 redirect URL is missing.
"""
# Swagger UI 5.33 introduced virtualization, so Ctrl+F misses endpoints
# that haven't been rendered. Pin 5.32.15 to keep browser Find working.
assets = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.32.15"
openapi_url = self.app.openapi_url
oauth2_redirect_url = self.app.swagger_ui_oauth2_redirect_url
if openapi_url is None or oauth2_redirect_url is None:
raise ValueError("Swagger UI requires OpenAPI and OAuth2 redirect URLs.")

async def swagger_ui_html(request: Request) -> HTMLResponse:
root_path = request.scope.get("root_path", "").rstrip("/")
# Recreate the docs page with the pinned JavaScript and CSS assets.
return get_swagger_ui_html(
openapi_url=root_path + openapi_url,
title=f"{self.app.title} - Swagger UI",
oauth2_redirect_url=root_path + oauth2_redirect_url,
swagger_js_url=f"{assets}/swagger-ui-bundle.js",
swagger_css_url=f"{assets}/swagger-ui.css",
)

async def swagger_ui_redirect(_request: Request) -> HTMLResponse:
return get_swagger_ui_oauth2_redirect_html()

self.app.add_route("/docs", swagger_ui_html, include_in_schema=False)
self.app.add_route(
oauth2_redirect_url, swagger_ui_redirect, include_in_schema=False
)

@classmethod
def from_things(
cls,
Expand Down
30 changes: 30 additions & 0 deletions tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,43 @@
"""

import pytest
from fastapi.testclient import TestClient
from starlette.routing import Route

import labthings_fastapi as lt
from labthings_fastapi.example_things import MyThing
from labthings_fastapi.server.config_model import ThingServerConfig


def test_swagger_ui_assets():
"""Check that the docs use the pinned assets and respect the root path."""
server = lt.ThingServer.from_things({})
with server.test_client() as client:
response = client.get("/docs")
response.raise_for_status()

assets = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.32.15"
assert f'{assets}/swagger-ui-bundle.js"' in response.text
assert f'{assets}/swagger-ui.css"' in response.text
assert "url: '/lab/openapi.json'" in response.text
assert "'/docs/oauth2-redirect'" in response.text
client.get("/docs/oauth2-redirect").raise_for_status()


@pytest.mark.parametrize(
"url_attribute", ["openapi_url", "swagger_ui_oauth2_redirect_url"]
)
def test_swagger_ui_requires_urls(url_attribute):
"""Raise ValueError if either URL required by Swagger UI is missing."""
server = lt.ThingServer.from_things({})
setattr(server.app, url_attribute, None)

with pytest.raises(
ValueError, match="Swagger UI requires OpenAPI and OAuth2 redirect URLs"
):
server._add_swagger_ui()


def test_server_from_config_non_thing_error():
"""Test a typeerror is raised if something that's not a Thing is added."""
with pytest.raises(TypeError, match="not a Thing"):
Expand Down
Loading