7 - Body: Fields#
You can declare validation and metadata inside of Pydantic models using Field
.
from pydantic import BaseModel, Field
class Item(BaseModel):
name: str
description: str | None = Field(
default=None, title="The description of the item", max_length=300
)
price: float = Field(gt=0, description="The price must be greater than zero")
tax: float | None = None
@app.put("/items11/{item_id}")
async def update_item(item_id: int, item: Annotated[Item, Body(embed=True)]):
results = {"item_id": item_id, "item": item}
return results
import requests
url = 'http://127.0.0.1:8000'
json_data = {
'item': {
'name': 'Pokeball',
'description': 'A capsule used for capturing Pokemon.',
'price': 1.50,
'tax': 0.50
}
}
requests.put(url + '/items11/123', json=json_data).json()
{'item_id': 123,
'item': {'name': 'Pokeball',
'description': 'A capsule used for capturing Pokemon.',
'price': 1.5,
'tax': 0.5}}