Handling form parameters
When API methods are designed to handle web forms, the services involved are required to retrieve form parameters instead of the request body because this form data is normally encoded as an application/x-www-form-urlencoded
media type. These form parameters are conventionally string
types, but the pydantic
module’s JSON encoder can convert each parameter value to its respective valid type.
All the form parameter variables can be declared required, with default values, or optional using the same set of Python types we used previously. Then, the fastapi
module has a Form
function that needs to be imported to initialize these form parameter variables during their declaration. To set these form parameters as required, the Form()
function must have the ellipses (…
) argument, thus calling it as Form(…)
:
from fastapi import FastAPI, Form @app.post("/ch01/account/profile/add", response_model=UserProfile) def add_profile(uname: str, fname: str = Form(...), lname: str = Form(...), mid_init: str = Form(...), user_age: int = Form(...), sal: float = Form(...), bday: str = Form(...), utype: UserType = Form(...)): if valid_users.get(uname) == None: return UserProfile(firstname=None, lastname=None, middle_initial=None, age=None, birthday=None, salary=None, user_type=None) else: profile = UserProfile(firstname=fname, lastname=lname, middle_initial=mid_init, age=user_age, birthday=datetime.strptime(bday, '%m/%d/%Y'), salary=sal, user_type=utype) valid_profiles[uname] = profile return profile
The preceding add_profile()
service shows us how to call the Form(…)
function to return a Form
object during the parameter declaration.
Important note
Form-handling services will not work if the python-multipart
module is not installed.
Sometimes, we need browser cookies to establish an identity for our application, leave trails in the browser for every user transaction, or store product information for a purpose. If FastAPI can manage form data, it can also do the same with cookies.