6 - Body: Multiple Parameters

6 - Body: Multiple Parameters#

Instead of expecting a JSON body with attributes, you can also declare an endpoint to expect multiple JSON bodies:

from fastapi import FastAPI
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: str | None = None
    price: float
    tax: float | None = None

class User(BaseModel):
    username: str
    full_name: str | None = None

@app.put("/items9/{item_id}")
async def update_item(item_id: int, item: Item, user: User):
    results = {"item_id": item_id, "item": item, "user": user}
    return results
import requests
url = 'http://127.0.0.1:8000'
item_data = {
    'name': 'Pokeball',
    'description': 'Used to catch wild Pokemon',
    'price': 1.50,
    'tax': 0.50
}
user_data = {
    'username': 'GottaKetchumAll',
    'full_name': 'Ash Ketchum'
}
json_data = {
    'item': item_data,
    'user': user_data
}
requests.put(url + '/items9/100', json=json_data).json()
{'item_id': 100,
 'item': {'name': 'Pokeball',
  'description': 'Used to catch wild Pokemon',
  'price': 1.5,
  'tax': 0.5},
 'user': {'username': 'GottaKetchumAll', 'full_name': 'Ash Ketchum'}}

Singular Values in Body#

In the same way that we have Query and Path to define extra data for query and path parameters, we have Body to define data for body parameters.

from fastapi import Body

@app.put("/items10/{item_id}")
async def update_item(
    item_id: int, item: Item, user: User, importance: Annotated[int, Body()]
):
    results = {"item_id": item_id, "item": item, "user": user, "importance": importance}
    return results
json_data = {
    'item': item_data,
    'user': user_data,
    'importance': 5
}
requests.put(url + '/items10/100', json=json_data).json()
{'item_id': 100,
 'item': {'name': 'Pokeball',
  'description': 'Used to catch wild Pokemon',
  'price': 1.5,
  'tax': 0.5},
 'user': {'username': 'GottaKetchumAll', 'full_name': 'Ash Ketchum'},
 'importance': 5}