FastAPI - HTML Form Templates

Let us add another route "/login" to our application which renders a html template having a simple login form. The HTML code for login page is as follows −

      <form action="/submit" method="POST">
         <h3>Enter User name</h3>
         <p><input type='text' name='nm'/></p>
         <h3>Enter Password</h3>
         <p><input type='password' name='pwd'/></p>
         <p><input type='submit' value='Login'/></p>

Note that the action parameter is set to "/submit" route and action set to POST. This will be significant for further discussion.

Add login() function in the file as under −

@app.get("/login/", response_class=HTMLResponse)
async def login(request: Request):
   return templates.TemplateResponse("login.html", {"request": request})

The URL http://localhost:8000/login will render the login form as follows −

FastAPI HTML Form Templates