Forms and Templates in FastAPI with Python

FastAPI is well-known for its outstanding performance when creating APIs, but it also handles conventional web content, such as HTML forms and templates, with ease. We will go over the specifics of using forms and templates in FastAPI in this blog post, breaking down each topic with examples in Python.

Forms in FastAPI

Handling HTML Forms:

FastAPI uses the Form dependency to handle data from HTML forms. Make sure you have installed the python-multipart package before continuing:

Bash

pip install python-multipart

Let’s consider an example where we retrieve a value from a GET form. In the FastAPI app, define a new path function, greet2():

Python

from fastapi import FastAPI, Form

app = FastAPI()

@app.get(“/who2”)

def greet2(name: str = Form()):

return f”Hello, {name}?”

Here, the value comes from the Form dependency instead of other sources like Path or Query.

Handling Form Requests:

To test the form, use HTTPie with the following command:

Bash

http -f -b GET localhost:8000/who2 name=”Bob Fr”

This sends a GET request with the form-encoded data, providing the response “Hello, Bob Frapples?”

Dealing with HTML Form Files:

Create an HTML file (form1.html) in the static directory. Here’s an example form:

Html

<form action=”http://localhost:8000/who2″ method=”GET”>

  Say hello to my little friend:

  <input type=”text” name=”name” value=”Bob Frapples”>

  <input type=”submit”>

</form>

Load this form in your browser, fill in a test string, and you should see the response.

Addressing HTML Weirdness:

If the form sends the name as a query parameter instead of a form field, it’s an HTML weirdness. Change the form action from GET to POST:

Python

@app.post(“/who2”)

def greet3(name: str = Form()):

return f”Hello, {name}?”

Update the HTML form accordingly, and now it should work as expected.

Templates in FastAPI

Introducing Jinja Templates:

FastAPI supports template engines, including Jinja. Create a directory named ‘templates’ to store your template files. For example, create a file named ‘list.html’:

Html

<html>

<!– … (Table structure) … –>

  {% for creature in creatures: %}

<tr>

<td>{{ creature.name }}</td>

<td>{{ creature.description }}</td>

<td>{{ creature.country }}</td>

<td>{{ creature.area }}</td>

<td>{{ creature.aka }}</td>

</tr>

{% endfor %}

<!– … (Table structure for explorers) … →

</html>

This template expects Python variables called creatures and explorers.

Using Templates in FastAPI:

Configure templates in your FastAPI app and use them in a path function:

Python

from fastapi import FastAPI, Request

from fastapi.templating import Jinja2Templates

from pathlib import Path

app = FastAPI()

top = Path(__file__).resolve().parent

template_obj = Jinja2Templates(directory=f”{top}/templates”)

# … (Fake data import) …

@app.get(“/list”)

def explorer_list(request: Request):

return template_obj.TemplateResponse(“list.html”, {“request”: request, “explorers”: fake_explorers, “creatures”: fake_creatures})

Now, accessing “http://localhost:8000/list” should render the HTML template.

We have looked at how FastAPI handles forms and templates. FastAPI provides a comprehensive solution for both API-centric and traditional web development tasks, ranging from working with HTML forms and addressing quirks to leveraging powerful template engines like Jinja. By mastering these concepts, developers can easily integrate form handling and dynamic content generation into their FastAPI applications.

 

Visited 1 times, 1 visit(s) today