2 - Request Body

2 - Request Body#

To declare a request body, we use Pydantic models.

Data Model Setup#

from pydantic import BaseModel

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

@app.post("/items/")
async def create_item(item: Item):
    return item

You can pass data in with a POST request using the json parameter for the payload:

import requests
url = 'http://127.0.0.1:8000'

payload = {
    'name': 'Towel',
    'price': 8.76
}
requests.post(url + '/items', json=payload).json()
{'name': 'Towel', 'description': None, 'price': 8.76, 'tax': None}

Using the Model#

@app.post("/items/")
async def create_item(item: Item):
    item_dict = item.dict()
    if item.tax is not None:
        price_with_tax = item.price + item.tax
        item_dict.update({"price_with_tax": price_with_tax})
    return item_dict
payload = {
    'name': 'Towel',
    'description': 'A towel',
    'price': 8.76,
    'tax': 1.15
}
requests.post(url + '/items', json=payload).json()
{'name': 'Towel',
 'description': 'A towel',
 'price': 8.76,
 'tax': 1.15,
 'price_with_tax': 9.91}