Body - Multiple Parameters

Now that we have seen how to use Path and Query, let's see more advanced uses of request body declarations.

Mix Path, Query and body parameters

First, of course, you can mix Path, Query and request body parameter declarations freely and FastAPI will know what to do.

And you can also declare body parameters as optional, by setting the default to None:

fromfastapiimportFastAPI,PathfrompydanticimportBaseModelapp=FastAPI()classItem(BaseModel):name:strdescription:str=Noneprice:floattax:float=None@app.put("/items/{item_id}")asyncdefupdate_item(*,item_id:int=Path(...,title="The ID of the item to get",ge=0,le=1000),q:str=None,item:Item=None,):results={"item_id":item_id}ifq:results.update({"q":q})ifitem:results.update({"item":item})returnresults

Note

Notice that, in this case, the item that would be taken from the body is optional. As it has a None default value.

Multiple body parameters

In the previous example, the path operations would expect a JSON body with the attributes of an Item, like:

{"name":"Foo","description":"The pretender","price":42.0,"tax":3.2}

But you can also declare multiple body parameters, e.g. item and user: