Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

FastAPI Form Data

FastAPI Form Data

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 the form feature, you need to install python-multipart:

pip install python-multipart


Receive Form Data

Use Form 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

}


Differences Between Form Fields and JSON Request Bodies

Comparison Item 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 endpoints (front-end/back-end separation) HTML form submission

Form data is sent in the form of "fields", not JSON. Therefore you cannot declare the Form parameter as a Pydantic model. Form fields and a JSON request body cannot be used in the same route at the same time.


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, defaults to None

    price:

float

=

Form

(

...

,

gt

=

0

)

,

         

Required, must be greater than 0

)

:

   

return

{

"name"

: name

,

"description"

: description

,

"price"

: price

}


Testing with an HTML Form

You can create an HTML page to test form submission:

Example

   

   

   


   

   

   


   

   

   


   


Validation and Documentation of Form Data

Use Form declared fields, FastAPI automatically performs data validation and displays them in the API documentation:


Summary