Manual wiring¶
setup() is optional. The content generators build the same pages, so you can write the routes yourself and pass what setup() doesn't accept, such as your own page titles or disable_search=True.
Each page needs its companion route. Swagger UI:
import fastapi_csp_docs
app = FastAPI(docs_url=None, redoc_url=None)
@app.get("/docs", include_in_schema=False)
async def swagger_ui_html() -> HTMLResponse:
return fastapi_csp_docs.get_swagger_ui_html(
title="Items API reference",
swagger_ui_init_script_url="/docs/swagger-initializer.js",
)
@app.get("/docs/swagger-initializer.js", include_in_schema=False)
async def swagger_ui_init_js() -> Response:
return fastapi_csp_docs.get_swagger_ui_init_js(
openapi_url=app.openapi_url,
oauth2_redirect_url="/docs/oauth2-redirect",
)
The OAuth2 redirect, needed only for OAuth2 login in Swagger UI:
@app.get("/docs/oauth2-redirect", include_in_schema=False)
async def oauth2_redirect_html() -> HTMLResponse:
return fastapi_csp_docs.get_swagger_ui_oauth2_redirect_html(
oauth2_redirect_script_url="/docs/oauth2-redirect.js",
)
@app.get("/docs/oauth2-redirect.js", include_in_schema=False)
async def oauth2_redirect_js() -> Response:
return fastapi_csp_docs.get_swagger_ui_oauth2_redirect_js()
ReDoc:
@app.get("/redoc", include_in_schema=False)
async def redoc_html() -> HTMLResponse:
return fastapi_csp_docs.get_redoc_html(
openapi_url=app.openapi_url,
title="Items API guide",
redoc_css_url="/redoc/redoc.css",
disable_search=True,
)
@app.get("/redoc/redoc.css", include_in_schema=False)
async def redoc_css() -> Response:
return fastapi_csp_docs.get_redoc_css()
Asset URLs you leave out take the pinned defaults.
root_path¶
The generators use URLs as given. setup() adds the root_path on each request; in your own routes, read it from the request scope:
@app.get("/docs", include_in_schema=False)
async def swagger_ui_html(request: Request) -> HTMLResponse:
root_path = request.scope.get("root_path", "").rstrip("/")
return fastapi_csp_docs.get_swagger_ui_html(
title="Items API reference",
swagger_ui_init_script_url=f"{root_path}/docs/swagger-initializer.js",
)
examples/self_hosted_manual_app.py wires every route with self-hosted assets.