Matheus
Matheus

Reputation: 219

How to remove "- Swagger UI" from HTML Page title of OpenAPI docs in FastAPI?

I am trying to customize my OpenAPI (Swagger UI) docs generated by FastAPI, but the string - Swagger UI in the title still remains.

app = FastAPI(
    title="Test",
    version="0.1.0"
)

HTML result :

<title>Test - Swagger UI</title>

Is there a way to remove this - Swagger UI from the title?

Upvotes: 5

Views: 3409

Answers (2)

Chris
Chris

Reputation: 34481

The - Swagger UI part is added to the title by FastAPI itself. In order to change that, you would need to override the /docs route, as shown in the documentation on how to self-host the JS and CSS files for /docs. FastAPI provides the CDN URLs for JS and CSS files, and hence, you could pass those to the parameters below (you don't necessarily need to download and serve them as static files). These are:

swagger_js_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js",
swagger_css_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css"

However, if you are not about to customise the /docs, but just want to change the title, you could simply omit from setting them on your own in the get_swagger_ui_html() function below, and thus, the default CDN URLs would be used by default, regardless.

Example

from fastapi import FastAPI
from fastapi.openapi.docs import get_swagger_ui_html
    
app = FastAPI(title ="Test", docs_url=None)
    
    
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
    return get_swagger_ui_html(
        openapi_url=app.openapi_url,
        title=app.title)

Upvotes: 1

cosmic_inquiry
cosmic_inquiry

Reputation: 2684

The way I got this to work is as follows:

from fastapi import FastAPI
from fastapi.openapi.docs import get_swagger_ui_html

app = FastAPI(
    title="Docs Title",
    description="Documentation ...",
    version="1.0.0",
    docs_url=None,
    redoc_url=None
)

@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
    return get_swagger_ui_html(
        openapi_url=app.openapi_url,
        title=app.title,
    )

This essentially forces fastapi to use the defined app.get("/docs") endpoint instead of the default.

Upvotes: 0

Related Questions