Skip to content
devtoolbox.cc

FastAPI · Chapter 4 of 6

FastAPI forms, Jinja2 templates, file uploads and static files

15 min study · Examples checked with FastAPI 0.163 and Jinja2 on Python 3.14 ·

JSON APIs talk to JavaScript and other programs. Plain HTML forms talk to FastAPI directly, without any JavaScript: the browser sends the fields in a different encoding, expects HTML back, and needs to be redirected after a successful submission. This chapter builds a “suggest a lesson” form with server-side validation, shows file uploads, and serves a stylesheet. Jinja2 and python-multipart, which it needs, come with fastapi[standard].

The application

The project has main.py, a templates folder and a static folder holding site.css, any small stylesheet.

from pathlib import Path
from typing import Annotated

from fastapi import FastAPI, Form, HTTPException, Request, UploadFile, status
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates

BASE = Path(__file__).resolve().parent
app = FastAPI()
app.mount("/static", StaticFiles(directory=BASE / "static"), name="static")
templates = Jinja2Templates(directory=BASE / "templates")
SUGGESTIONS: list[dict] = []


@app.get("/suggest", response_class=HTMLResponse)
def suggest_form(request: Request):
    return templates.TemplateResponse(request, "suggest.html", {"errors": [], "values": {}})


@app.post("/suggest", response_class=HTMLResponse)
def suggest(
    request: Request,
    name: Annotated[str, Form()],
    topic: Annotated[str, Form()],
    level: Annotated[str, Form()] = "beginner",
):
    values = {"name": name.strip(), "topic": topic.strip(), "level": level}
    errors = []
    if not values["name"]:
        errors.append("Please enter your name.")
    if len(values["topic"]) < 3:
        errors.append("The topic needs at least 3 characters.")
    if level not in {"beginner", "advanced"}:
        errors.append("Choose a level from the list.")
    if errors:
        return templates.TemplateResponse(
            request, "suggest.html", {"errors": errors, "values": values}, status_code=422
        )
    SUGGESTIONS.append(values)
    return RedirectResponse("/suggest/thanks", status_code=status.HTTP_303_SEE_OTHER)


@app.get("/suggest/thanks", response_class=HTMLResponse)
def thanks():
    return f"<p>Thank you! {len(SUGGESTIONS)} suggestion(s) so far.</p>"


@app.post("/notes/upload")
async def upload_notes(file: UploadFile):
    if file.content_type != "text/plain":
        raise HTTPException(status_code=415, detail="Only plain text files are accepted")
    data = await file.read(100_001)
    if len(data) > 100_000:
        raise HTTPException(status_code=413, detail="File larger than 100 kB")
    text = data.decode("utf-8")
    return {"filename": file.filename, "lines": len(text.splitlines())}

The template uses Jinja2 syntax: {{ ... }} prints a value and {% ... %} runs logic such as if and for.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Suggest a lesson</title>
    <link rel="stylesheet" href="{{ url_for('static', path='site.css') }}">
  </head>
  <body>
    <h1>Suggest a lesson</h1>
    <ul class="errors">{% for e in errors %}<li>{{ e }}</li>{% endfor %}</ul>
    <form method="post" action="/suggest">
      <label>Your name <input name="name" value="{{ values.name or '' }}" required></label>
      <label>Topic <input name="topic" value="{{ values.topic or '' }}" minlength="3" required></label>
      <label>Level
        <select name="level">
          <option value="beginner">Beginner</option>
          <option value="advanced" {% if values.level == 'advanced' %}selected{% endif %}>Advanced</option>
        </select>
      </label>
      <button>Send</button>
    </form>
  </body>
</html>

Form data is not JSON

A form with method="post" sends its fields as application/x-www-form-urlencoded, the same name=Ada&topic=Generators encoding as a query string, in the request body. In FastAPI you read each field with a Form() parameter. Sending JSON to the same route doesn’t work: the fields are missing, and FastAPI answers 422 with loc ["body", "name"]. A route serves either forms or JSON, so if an API needs both, give them separate endpoints.

The input attributes required and minlength make the browser check fields before sending. That improves the experience, but anyone can bypass it with a script or the developer tools, so the server repeats every check. Field names in the HTML must match the parameter names exactly.

Validate, re-render, redirect

The handler validates by hand so it can respond the way people expect from a web page: the form is shown again with every problem listed and the entered values kept. Posting name=" ", topic="<b>AI</b>", level="expert" returns status 422 with this list:

Please enter your name.
Choose a level from the list.

and the topic field filled in with &lt;b&gt;AI&lt;/b&gt;. Jinja2 templates created through Jinja2Templates escape every value printed with {{ }}, so text a user typed appears as text rather than running as HTML. That automatic escaping is the main defence against cross-site scripting; never turn it off for user input (the |safe filter does that). The select value is checked on the server too, since a forged request can send anything.

On success the handler stores the suggestion and returns a 303 redirect to /suggest/thanks. This is the post/redirect/get pattern. The browser follows the redirect with a GET, so the page the user sees came from a GET request, and pressing refresh reloads the thank-you page instead of submitting the form a second time.

The suggestions live in a module-level list, which vanishes on restart and isn’t shared between worker processes. Chapter 6 replaces it with a database. A public form also needs protection this example leaves out: rate limiting against spam, and a CSRF token if users are logged in with cookies (the Django track shows how a framework does this for you).

File uploads

A form with enctype="multipart/form-data" and an <input type="file" name="file"> uploads files; API clients send the same format. An UploadFile parameter receives the file without loading it into memory first. Uploading a two-line week1.txt returns {"filename": "week1.txt", "lines": 2}; a PNG gets 415 Only plain text files are accepted.

UploadFile offers filename, content_type and async read. Everything about an upload comes from the client and can be false: the content type is only a claim, and the file name can contain ../ or characters your file system rejects. The handler therefore limits the size it will read (reading one byte more than the limit tells it whether the file is too big), and decoding with UTF-8 would fail loudly on binary data, which you can catch for a 400 response. When storing uploads, generate your own file names, keep them outside any folder served as static files, and check the size before writing.

Static files

app.mount("/static", StaticFiles(directory=...)) serves every file in that folder under /static/..., with the right content type: /static/site.css comes back as text/css. Requests can’t climb out of the folder; /static/../main.py returns 404. Only mount a folder that contains nothing secret, never the project root.

In templates, url_for('static', path='site.css') builds the URL from the mount’s name, so moving the mount later doesn’t break links. Paths are built from Path(__file__).resolve().parent, so the app finds its folders whichever directory it is started from.

Practice

Add a GET /suggestions page that lists all stored suggestions in a table using a new template, newest first, and add an optional email field to the form that, when filled in, must contain exactly one @. Then post a suggestion whose topic is <script>alert(1)</script> and look at the HTML of the list page.

Answer check: pass reversed(SUGGESTIONS) or a sorted copy to the template and loop with {% for s in suggestions %}. The script text appears escaped as &lt;script&gt;... and doesn’t run. Validate the email in the same error list (email and email.count("@") != 1), keep the entered value on errors, and leave real address checking to a confirmation email.

Summary

HTML forms send URL-encoded fields that Form() parameters read; they are not JSON. Repeat every browser-side check on the server, re-render the form with errors and kept values, and answer a successful POST with a 303 redirect. Jinja2 escapes output by default, UploadFile handles uploads that you must size-check and distrust, and StaticFiles serves assets from a dedicated folder.

All FastAPI chapters