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

FastAPI Request Body

FastAPI Request Body

The request body is the data the client sends to the API. When you need to receive JSON data from the client, use the request body. FastAPI uses Pydantic models to declare the structure of the request body, automatically handling validation, conversion, and documentation generation.


Difference between request body and query parameters

Data transfer method Position Applicable scenarios HTTP methods
Path parameters URL path /items/5 Identify resources GET, PUT, DELETE, etc.
Query Parameters In the URL ?key=value Optional parameters such as filtering and pagination Mainly GET
Request body Request JSON data Submit complex data POST、PUT、PATCH

To send data, you should use POST(most common),PUT、DELETE or PATCH. Although FastAPI technically supports GET requests carrying a request body, this does not conform to the HTTP specification, and Swagger UI will not display request body documentation for GET requests.


Declare the request body using a Pydantic model

1. Import BaseModel

from pydantic import BaseModel

2. Create a data model

Define a class that inherits from BaseModel , declaring all attributes using standard Python types:

Example

from

fastapi

import

FastAPI

from

pydantic

import

BaseModel

app

=

FastAPI

(

)

Define the request body data model

class

Item

(

BaseModel

)

:

    name:

str

             

Required: item name

    description:

str

|

None

=

None

 

Optional: item description

    price:

float

           

Required: item price

    tax:

float

|

None

=

None

       

Optional: tax

@

app.

post

(

"/items/"

)

async

def

create_item

(

item: Item

)

:

   

return

item

The rules for whether an attribute is required are the same as for query parameters:

The following JSON are all valid request bodies:

// 包含所有字段

{

    "name": "Foo",

    "description": "可选描述",

    "price": 45.2,

    "tax": 3.5

}



// Omit optional fields

{

    "name": "Foo",

    "price": 45.2

}


How FastAPI handles request bodies

Just through Python type declarations, FastAPI can automatically do the following:

Function Description
Read the request body Read the data in the request in JSON format
Type Conversion Convert data to the declared type (e.g. string to float)
Data validation Validate the data and return clear error messages when it is invalid
Assign parameters Assign the validated data to function parameters, providing editor autocompletion
Generate documentation Automatically generate JSON Schema, which appears in the API documentation

Use model attributes

Inside the path operation function, you can access all attributes of the model just like a regular Python object:

Example

from

fastapi

import

FastAPI

from

pydantic

import

BaseModel

app

=

FastAPI

(

)

class

Item

(

BaseModel

)

:

    name:

str

    description:

str

|

None

=

None

    price:

float

    tax:

float

|

None

=

None

@

app.

post

(

"/items/"

)

async

def

create_item

(

item: Item

)

:

   

Access model attributes directly

    item_dict

=

item.

model_dump

(

)

 

Pydantic v2 serialization methods

   

if

item.

tax

:

       

Calculate the tax-inclusive price

        price_with_tax

=

item.

price

tax

        item_dict.

update

(

{

"price_with_tax"

: price_with_tax

}

)

   

return

item_dict

Pydantic v2 uses model_dump() instead of v1's dict() method to serialize model data.model_dump() Returns a dictionary containing all fields of the model.


Request body + path parameters

You can declare path parameters and a request body at the same time, and FastAPI will automatically get data from the correct location:

Example

from

fastapi

import

FastAPI

from

pydantic

import

BaseModel

app

=

FastAPI

(

)

class

Item

(

BaseModel

)

:

    name:

str

    description:

str

|

None

=

None

    price:

float

    tax:

float

|

None

=

None

Using path parameters and a request body together

@

app.

put

(

"/items/{item_id}"

)

async

def

update_item

(

item_id:

int

,

item: Item

)

:

   

return

{

"item_id"

: item_id

,

"item_name"

: item.

name

}

FastAPI recognition rules:


Request body + path parameters + query parameters

All three can be used together:

Example

from

fastapi

import

FastAPI

from

pydantic

import

BaseModel

app

=

FastAPI

(

)

class

Item

(

BaseModel

)

:

    name:

str

    description:

str

|

None

=

None

    price:

float

    tax:

float

|

None

=

None

Using path parameters, query parameters, and a request body together

@

app.

put

(

"/items/{item_id}"

)

async

def

update_item

(

item_id:

int

,

item: Item

,

q:

str

|

None

=

None

)

:

    result

=

{

"item_id"

: item_id

,

**item.

model_dump

(

)

}

   

if

q:

        result.

update

(

{

"q"

: q

}

)

   

return

result

FastAPI's complete parameter recognition rules:

Recognition condition Parameter source
The parameter name is declared in the path's {} declare Path parameters
The parameter is a single type (int、str、bool etc.) Query Parameters
The parameter type is a Pydantic model Request body

Summary

Key points about request bodies: