How to Use Form in FastAPI: Simple Guide with Examples
In FastAPI, use
Form from fastapi to declare form fields in your endpoint functions. This allows your API to receive data sent as HTML form submissions by specifying parameters with Form(...).Syntax
To receive form data in FastAPI, import Form and use it to declare parameters in your path operation function. Each form field is a function parameter with a default value set by Form(...).
This tells FastAPI to expect the data from an HTML form submission instead of JSON.
python
from fastapi import FastAPI, Form app = FastAPI() @app.post("/login") async def login(username: str = Form(...), password: str = Form(...)): return {"username": username, "password": password}
Example
This example shows a FastAPI app with a POST endpoint /login that accepts username and password as form data. When you send a form submission, FastAPI extracts these values and returns them in JSON.
python
from fastapi import FastAPI, Form from fastapi.responses import HTMLResponse app = FastAPI() @app.get("/", response_class=HTMLResponse) async def form(): return """ <form action="/login" method="post"> <input name="username" type="text" placeholder="Username"> <input name="password" type="password" placeholder="Password"> <button type="submit">Login</button> </form> """ @app.post("/login") async def login(username: str = Form(...), password: str = Form(...)): return {"username": username, "password": password}
Output
When you open the root URL, you see a simple login form. Submitting it sends form data to /login, which returns JSON with the username and password you entered.
Common Pitfalls
- Forgetting to import
Formcauses errors or unexpected behavior. - Using
Formparameters with default values other than...(ellipsis) can make fields optional unintentionally. - Trying to receive form data without
Formwill make FastAPI expect JSON instead. - Mixing
FormandBodyparameters requires careful ordering and explicit declaration.
python
from fastapi import FastAPI from fastapi import Form app = FastAPI() # Wrong: missing Form import and usage @app.post("/wrong") async def wrong(username: str, password: str): return {"username": username, "password": password} # Right: @app.post("/right") async def right(username: str = Form(...), password: str = Form(...)): return {"username": username, "password": password}
Quick Reference
FastAPI Form Usage Cheat Sheet:
- Import
Formfromfastapi. - Declare form fields as function parameters with
= Form(...). - Use
Form(...)to make fields required. - Use
Form(None)to make fields optional. - Works only with
application/x-www-form-urlencodedormultipart/form-datacontent types.
Key Takeaways
Use Form(...) in endpoint parameters to receive HTML form data in FastAPI.
Always import Form from fastapi to avoid errors.
Form fields declared with Form(...) are required by default.
Form works with form-encoded or multipart form data, not JSON.
Mixing Form and Body parameters requires explicit declarations.