Handling Forms in FASTAPI

Table of contents

My Files Structure:

  • main.py

  • Static

    • Any CSS, JS, IMAGES
  • templates

    • Form.html

    • display.html

main.py

from fastapi import FastAPI,Request,Form
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("/",response_class=HTMLResponse)
def homepage(request : Request):
    return templates.TemplateResponse("Form.html",{"request":request})

@app.post("/url_to_handle",response_class=HTMLResponse)
async def homepage(request : Request, name_id : str = Form(...),age_id : int = Form(...)):

    return templates.TemplateResponse("display.html",{"request":request,"stud_name":name_id,"stud_age":age_id})

Let me brief You above Python code:

  • app - Created an instance Of FastAPI

  • TemplateResponse - to render the HTML File

  • age_id: int = Form(...) (id of the field) : (Type Expected in python) = Form(...) is how we get the age field.

  • Passing the values to the display.html page {"request": request, "stud_name":name_id, "stud_age":age_id} This is similar to Python dictionary and we access through Keys but are of JSON.

How to Run

Its better to create Virtual Environment and run in it.

If you want to create Virtual Environment Go to Your Project Folder

python -m venv environment_name_you_want_to_use

How to activate the Virtual Environment

environment_name_you_want_to_use\Scripts\activate

How to run the app:

uvicorn test:app

To stop rerunning the app after every change made in it, You can use the following way:

uvicorn test:app --reload

Form.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form</title>
</head>
<body>
    <form action="/url_to_handle" method="post">
        <label for="Name">Enter Name:</label>
        <input type="text" name="name_id">
        <label for="age">Enter Age:</label>
        <input type="number" name="age_id">
        <input type="submit" value="Submit Button">
    </form>
</body>
</html>

display.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Result</title>
</head>
<body>
    <p>Hi<h1>{{stud_name}}</h1></p>
    <p>Your Age is<h1>{{stud_age}}</h1></p>
</body>
</html>

Why FastAPI?

FastAPI is a modern, high-performance web framework for building APIs with Python based on standard type hints. It has the following key features:

  • Fast to run: It offers very high performance, on par with NodeJS and Go, thanks to Starlette and pydantic.

  • Fast to code: It allows for significant increases in development speed.

  • Reduced number of bugs: It reduces the possibility for human-induced errors.

  • Intuitive: It offers great editor support, with completion everywhere and less time debugging.

  • Straightforward: It’s designed to be uncomplicated to use and learn, so you can spend less time reading documentation.

  • Short: It minimizes code duplication.

  • Robust: It provides production-ready code with automatic interactive documentation.

  • Standards-based: It’s based on the open standards for APIs, OpenAPI and JSON Schema.