11# Form Models
22
3- You can use Pydantic models to declare form fields in FastAPI.
3+ You can use ** Pydantic models** to declare ** form fields** in FastAPI.
44
55/// info
66
@@ -22,7 +22,7 @@ This is supported since FastAPI version `0.113.0`. 🤓
2222
2323## Pydantic Models for Forms
2424
25- You just need to declare a Pydantic model with the fields you want to receive as form fields, and then declare the parameter as ` Form ` :
25+ You just need to declare a ** Pydantic model** with the fields you want to receive as ** form fields** , and then declare the parameter as ` Form ` :
2626
2727//// tab | Python 3.9+
2828
@@ -54,7 +54,7 @@ Prefer to use the `Annotated` version if possible.
5454
5555////
5656
57- FastAPI will extract the data for each field from the form data in the request and give you the Pydantic model you defined.
57+ ** FastAPI** will ** extract** the data for ** each field** from the ** form data** in the request and give you the Pydantic model you defined.
5858
5959## Check the Docs
6060
@@ -63,3 +63,72 @@ You can verify it in the docs UI at `/docs`:
6363<div class =" screenshot " >
6464<img src =" /img/tutorial/request-form-models/image01.png " >
6565</div >
66+
67+ ## Restrict Extra Form Fields
68+
69+ In some special use cases (probably not very common), you might want to ** restrict** the form fields to only those declared in the Pydantic model. And ** forbid** any ** extra** fields.
70+
71+ /// note
72+
73+ This is supported since FastAPI version ` 0.114.0 ` . 🤓
74+
75+ ///
76+
77+ You can use Pydantic's model configuration to ` forbid ` any ` extra ` fields:
78+
79+ //// tab | Python 3.9+
80+
81+ ``` Python hl_lines="12"
82+ {!> ../ ../ ../ docs_src/ request_form_models/ tutorial002_an_py39.py!}
83+ ```
84+
85+ ////
86+
87+ //// tab | Python 3.8+
88+
89+ ``` Python hl_lines="11"
90+ {!> ../ ../ ../ docs_src/ request_form_models/ tutorial002_an.py!}
91+ ```
92+
93+ ////
94+
95+ //// tab | Python 3.8+ non-Annotated
96+
97+ /// tip
98+
99+ Prefer to use the ` Annotated ` version if possible.
100+
101+ ///
102+
103+ ``` Python hl_lines="10"
104+ {!> ../ ../ ../ docs_src/ request_form_models/ tutorial002.py!}
105+ ```
106+
107+ ////
108+
109+ If a client tries to send some extra data, they will receive an ** error** response.
110+
111+ For example, if the client tries to send the form fields:
112+
113+ * ` username ` : ` Rick `
114+ * ` password ` : ` Portal Gun `
115+ * ` extra ` : ` Mr. Poopybutthole `
116+
117+ They will receive an error response telling them that the field ` extra ` is not allowed:
118+
119+ ``` json
120+ {
121+ "detail" : [
122+ {
123+ "type" : " extra_forbidden" ,
124+ "loc" : [" body" , " extra" ],
125+ "msg" : " Extra inputs are not permitted" ,
126+ "input" : " Mr. Poopybutthole"
127+ }
128+ ]
129+ }
130+ ```
131+
132+ ## Summary
133+
134+ You can use Pydantic models to declare form fields in FastAPI. 😎
0 commit comments