Skip to content

Hiding docs tip #4

Description

@igorbenav

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)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions