1

I have a FastAPI app that returns an HTMLResponse. The code is simple and straightforward as the examples in FastAPI's documentation. The response works fine, but Swagger UI displays the raw HTML content. Is there a way to display the actual HTML page?

FastAPI app:

from fastapi import FastAPI
from fastapi.responses import HTMLResponse

app = FastAPI()


@app.get("/items/")
async def read_items():
    html_content = """
    <html>
        <head>
            <title>Some HTML in here</title>
        </head>
        <body>
            <h1>Look ma! HTML!</h1>
        </body>
    </html>
    """
    return HTMLResponse(content=html_content, status_code=200)

Response: enter image description here

Chris
  • 18,724
  • 6
  • 46
  • 80
user14681827
  • 143
  • 1
  • 10
  • Does this answer your question? [How to get HTML page displayed in Swagger UI (Flask)](https://stackoverflow.com/q/66401948/113116) – Helen Nov 11 '22 at 09:39

1 Answers1

3

This is the expected behaviour by Swagger UI (see here as well). Swagger UI correctly displays the response body, and not how that response would be interpeted by a user-agent; more specifically, a Web browser. That being said, if you return an image using a FileResponse (including the correct media_type, which would automatically be added by FastAPI if left unset, by using the file's extension to infer the media_type), you would see that Swagger UI will actually display the image (instead of the image bytes as text). However, this is not the case when it comes to HTML content.

There was a discussion around this topic, but the idea was rejected due to security risks. Someone has made a suggestion of having a Show Preview button, which would preview the HTML content returned in a response and allow the user to interact with; however, this has not been officially implemented yet.

I should also mention that OpenAPI supports markdown elements, as well as standard HTML tags, which you can use in the description property to display images, links, etc. Have a look at this answer.

Chris
  • 18,724
  • 6
  • 46
  • 80