-
-
Notifications
You must be signed in to change notification settings - Fork 127
Open
Description
This is a question I see people asking a lot, so might be useful.
Removing fastapi docs completely:
import FastAPI
application = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
Injecting a dependency (like get_current_superuser so only superusers are allowed to access the docs)
import FastAPI
from fastapi import Depends
from fastapi.openapi.docs import get_redoc_html, get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
from .dependencies import get_current_superuser
# let's just remove the standard docs urls
application = FastAPI(
docs_url=None,
redoc_url=None,
openapi_url=None,
title="My API",
version="0.1.0",
)
# and create the router with the dependency we want
docs_router = APIRouter(dependencies=[Depends(get_current_superuser)])
# and rewrite the endpoints
@docs_router.get("/docs", include_in_schema=False)
async def get_swagger_documentation() -> fastapi.responses.HTMLResponse:
return get_swagger_ui_html(openapi_url="/openapi.json", title="docs")
@docs_router.get("/redoc", include_in_schema=False)
async def get_redoc_documentation() -> fastapi.responses.HTMLResponse:
return get_redoc_html(openapi_url="/openapi.json", title="docs")
@docs_router.get("/openapi.json", include_in_schema=False)
async def openapi() -> dict[str, Any]:
out: dict = get_openapi(title=application.title, version=application.version, routes=application.routes)
return out
# finally, let's include these in the original FastAPI application
application.include_router(docs_router)
paudelgaurav, jpjacobpadilla, hgalytoby, the-lay, jason810496 and 6 morehgalytobyhgalytobyhgalytoby, tobiasz-gleba and jd-solankihgalytoby and jd-solanki
Metadata
Metadata
Assignees
Labels
No labels