Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hiding docs tip #4

Open
igorbenav opened this issue Apr 28, 2024 · 0 comments
Open

Hiding docs tip #4

igorbenav opened this issue Apr 28, 2024 · 0 comments

Comments

@igorbenav
Copy link

igorbenav commented Apr 28, 2024

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant