Concepts 🚀 Project 🧮 Labs
🧮 Labs / FastAPI / Forms — Form() instead of JSON body

Forms — Form() instead of JSON body

HTML forms send application/x-www-form-urlencoded, not JSON. Use Form(...) to receive.

main.py v3.1
API simulator click Simulate
Click "Simulate" to see what this FastAPI app does.
🧠 How it works

Form(...) — like Body(...) but reads from form-encoded body. Each Form arg name MUST match the input name='' in HTML. HTML forms send form-encoded by default (key=value&key=value), not JSON. For file uploads: <form enctype='multipart/form-data'> + UploadFile = File(...). PRG pattern (Post/Redirect/Get): after a POST, redirect to a GET page — prevents the 'Confirm Form Resubmission' browser warning on refresh. Use status_code=303 (See Other) for the redirect — it's the correct code for PRG.

✏️ Try these changes
  • Add a new form field: message: str = Form(...)
    → add a textarea to the form
  • Change age: int = Form(...) to age: int = Form(0)
    → age becomes optional with default 0
  • Change RedirectResponse status_code from 303 to 302
    → still works, but 303 is technically correct for PRG
  • Add a checkbox: agree: bool = Form(False)
    → checkbox only sends a value when checked