YouTip LogoYouTip

Fastapi Form

When a client submits data through an HTML form (`application/x-www-form-urlencoded`), you need to use `Form` to receive form fields instead of `BaseModel`. * * * ## Install python-multipart Before using form functionality, you need to install `python-multipart`: pip install python-multipart * * * ## Receive Form Data Use `Form` to declare form fields: ## Example from fastapi import FastAPI, Form app = FastAPI() @app.post("/login/") async def login( username: str= Form(),# Required form field password: str= Form(),# Required form field ): return{"username": username} !(#) * * * ## Difference Between Form Fields and JSON Request Body | Comparison | JSON Request Body | Form Data | | --- | --- | --- | | Content-Type | `application/json` | `application/x-www-form-urlencoded` | | Declaration Method | Pydantic `BaseModel` | `Form()` | | Data Structure | Supports nested objects and arrays | Flat key-value pairs | | Applicable Scenarios | API interfaces (front-end and back-end separation) | HTML form submission | > Form data is sent as "fields", not JSON. Therefore, you cannot declare `Form` parameters as Pydantic models. Form fields and JSON request bodies cannot be used together in the same route. * * * ## Optional Form Fields Similar to query parameters, form fields with default values are optional: ## Example from fastapi import FastAPI, Form app = FastAPI() @app.post("/items/") async def create_item( name: str= Form(...),# Required description: str | None= Form(None),# Optional, default None price: float= Form(..., gt=0),# Required, must be greater than 0 ): return{"name": name,"description": description,"price": price} !(#) * * * ## Test Using HTML Form You can create an HTML page to test form submission: ## Example


* * * ## Form Data Validation and Documentation Fields declared with `Form`, FastAPI will automatically perform data validation and display it in the API documentation: !(#) !(#) * * * ## Summary * Use `Form` to receive data submitted from HTML forms * Form data is not JSON and cannot be mixed with `BaseModel` request body * `Form()` declares required fields, `Form(None)` declares optional fields * Need to install the `python-multipart` package * Form fields support the same validation rules as query parameters (`min_length`, `gt`, etc.)
← Java Variable Naming RulesFastapi Pydantic β†’