Is it possible to display an HTML file at the endpoint?
For example the home page then the user is visiting "/"
?
FastAPI is really designed for building APIs and microservices. It can be used for building web applications that serve HTML using Jinja, but that's not what it is really optimized for.
Return a Response Directly ¶ 1 Return a Response ¶. In fact, you can return any Response or any sub-class of it. ... 2 Using the jsonable_encoder in a Response ¶. Because FastAPI doesn't do any change to a Response you return, you have to make sure it's contents are ready for it. 3 Returning a custom Response ¶. ... 4 Notes ¶. ...
But as you passed the HTMLResponse in the response_class too, FastAPI will know how to document it in OpenAPI and the interactive docs as HTML with text/html: Here are some of the available responses.
A line break only makes sense if the response is an HTML response (i.e. an HTML page). And a does not render properly as new lines or line breaks, you have to use <br> or an HTML template + some CSS styling to preserve line breaks. FastAPI returns, by default, a JSONResponse type. Takes some data and returns an application/json encoded response.
If you use a response class with no media type, FastAPI will expect your response to have no content, so it will not document the response format in its generated OpenAPI docs. For example, if you are squeezing performance, you can install and use orjson and set the response to be ORJSONResponse.
Yes, it's possible FastAPI has HTMLResponse
.
You can return a HTMLResponse
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
app = FastAPI()
@app.get("/", response_class=HTMLResponse)
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)
You can also render templates with Jinja2
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
@app.get("/items/{id}", response_class=HTMLResponse)
async def read_item(request: Request, id: str):
return templates.TemplateResponse("item.html", {"request": request, "id": id}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With