Reading time: < 1 minute
Hello, today I’m going to show you how to return an HTML after calling an endpoint in FastAPI, the Python REST API:
The first thing is to import this dependency:
from fastapi.responses import HTMLResponse
Once imported, we’re going to create a “get” function that, when called by the URL in the browser, returns an HTML (in this case, a plain text HTML created as a string)
@user.post("/index", response_class=HTMLResponse, status_code=status.HTTP_200_OK) async def index(db_session: Session = Depends(get_db)) -> HTMLResponse: web_return = "<p>Hello World!</p>" return web_return
In this example, (besides using SQL sessions), I first created an endpoint “/index”, which will be called at: http://localhost:8000/index
Instead of specifying a response_model, we add a response_class of type HTMLResponse (previously imported).
Now we indicate that it returns an -> HTMLResponse.
Finally, a string with a web page is created and returned by the function.
The result is that when loading the URL http://localhost:8000/index, “Hello World” will appear on the screen.
We can combine this with returning a form built with the necessary data.
(Do not include the Reading time). Return it directly in HTML format. When you’re done, add a PIPE at the end.