- FastAPI - Home
- FastAPI - Introduction
- FastAPI - Hello World
- FastAPI - OpenAPI
- FastAPI - Uvicorn
- FastAPI - Type Hints
- FastAPI - IDE Support
- FastAPI - Rest Architecture
- FastAPI - Path Parameters
- FastAPI - Query Parameters
- FastAPI - Parameter Validation
- FastAPI - Pydantic
- FastAPI - Request Body
- FastAPI - Templates
- FastAPI - Static Files
- FastAPI - HTML Form Templates
- FastAPI - Accessing Form Data
- FastAPI - Uploading Files
- FastAPI - Cookie Parameters
- FastAPI - Header Parameters
- FastAPI - Response Model
- FastAPI - Nested Models
- FastAPI - Dependencies
- FastAPI - CORS
- FastAPI - Crud Operations
- FastAPI - SQL Databases
- FastAPI - Using MongoDB
- FastAPI - Using GraphQL
- FastAPI - Websockets
- FastAPI - FastAPI Event Handlers
- FastAPI - Mounting A Sub-App
- FastAPI - Middleware
- FastAPI - Mounting Flast App
- FastAPI - Deployment
FastAPI Useful Resources
FastAPI - HTML Form Templates
Let us add another route "/login" to our application created in FastAPI - Static Files Chapter which renders a html template having a simple login form. The HTML code for login page is as follows −
Example - Adding Login Page
login.html
<html>
<body>
<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>
</form>
</body>
</html>
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 main.py file as under −
main.py
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
app = FastAPI()
templates = Jinja2Templates(directory="templates")
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/hello/{name}", response_class=HTMLResponse)
async def hello(request: Request, name:str):
return templates.TemplateResponse("hello.html", {"request": request, "name":name})
@app.get("/login/", response_class=HTMLResponse)
async def login(request: Request):
return templates.TemplateResponse("login.html", {"request": request})
Output
The URL http://localhost:8000/login will render the login form as follows −
Advertisements