Form Data
When you need to receive form fields instead of JSON, you can use Form.
Import Form
Section titled “Import Form”Import Form from fastapi:
from typing import Annotated
from fastapi import FastAPI, Form
app = FastAPI()
@app.post("/login/")
async def login(username: Annotated[str, Form()], password: Annotated[str, Form()]):
return {"username": username}Define Form parameters
Section titled “Define Form parameters”Create form parameters the same way you would for Body or Query:
from typing import Annotated
from fastapi import FastAPI, Form
app = FastAPI()
@app.post("/login/")
async def login(username: Annotated[str, Form()], password: Annotated[str, Form()]):
return {"username": username}For example, in one of the ways the OAuth2 specification can be used (called "password flow") it is required to send a username and password as form fields.
The spec requires the fields to be exactly named username and password, and to be sent as form fields, not JSON.
With Form you can declare the same configurations as with Body (and Query, Path, Cookie), including validation, examples, an alias (e.g. user-name instead of username), etc.
About "Form Fields"
Section titled “About "Form Fields"”The way HTML forms (<form></form>) send the data to the server normally uses a "special" encoding for that data, it's different from JSON.
FastAPI will make sure to read that data from the right place instead of JSON.
Use Form to declare form data input parameters.