Skip to content

Commit 844c649

Browse files
author
redjax
committed
hotfix(fastapi-utils): Add fix_api_docs()
This was supposed to go out in the last release (v0.1.9) but was overwritten somehow.
1 parent 9db18fd commit 844c649

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

red_utils/fastapi_utils/__init__.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,13 @@
1616
tags_metadata,
1717
)
1818
from .dependencies import logging_dependency
19-
from .operations import add_cors_middleware, add_routers, get_app, update_tags_metadata
19+
from .operations import (
20+
add_cors_middleware,
21+
add_routers,
22+
get_app,
23+
update_tags_metadata,
24+
fix_api_docs,
25+
)
2026
from .tag_definitions import tags_metadata
2127
from .uvicorn_override import InterceptHandler, setup_uvicorn_logging
2228
from .validators import (

red_utils/fastapi_utils/operations.py

+26
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,32 @@
2323
from fastapi import APIRouter, FastAPI
2424
from fastapi.middleware.cors import CORSMiddleware
2525

26+
27+
def fix_api_docs(app: FastAPI = None):
28+
"""Fix error loading /docs when a root_path is set.
29+
30+
Call after declaring an app with a root_path set, for example:
31+
app = FastAPI(root_path="/some/path")
32+
fix_api_docs(app)
33+
34+
When a root_path is declared, the default /docs URL breaks, and returns
35+
an error:
36+
Fetch error
37+
Not Found /api/v1/openapi.json
38+
"""
39+
if not app:
40+
raise ValueError("Missing a FastAPI app with a root_path var declared")
41+
42+
if not isinstance(app, FastAPI):
43+
raise TypeError(
44+
f"Invalid type for FastAPI app: ({type(app)}). Value must be of type FastAPI."
45+
)
46+
47+
@app.get(app.root_path + "/openapi.json")
48+
def custom_swagger_ui_html():
49+
return app.openapi()
50+
51+
2652
def update_tags_metadata(
2753
tags_metadata: list = tags_metadata,
2854
update_metadata: Union[list[dict[str, str]], dict[str, str]] = None,

0 commit comments

Comments
 (0)