BudiBadu Logo
Samplebadu

FastAPI by Example: Body Payload Models

FastAPI 0.100+

Request bodies are used to send data from the client to the API. This example illustrates how to define a request body using Pydantic models for automatic validation and documentation.

Code

from fastapi import FastAPI
from pydantic import BaseModel
from typing import Union

class Item(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: float = 10.5

app = FastAPI()

@app.post("/items/")
async def create_item(item: Item):
    item_dict = item.dict()
    if item.tax:
        price_with_tax = item.price + item.tax
        item_dict.update({"price_with_tax": price_with_tax})
    return item_dict

Explanation

FastAPI uses Pydantic models to define the structure and data types of request bodies. By creating a class that inherits from BaseModel and declaring fields with standard Python types, you specify exactly what data your API expects. FastAPI reads the body as JSON, validates it against your model, and converts it into a Python object.

This validation is automatic. If a client sends a request with a missing required field or a value of the wrong type (e.g., a string instead of a float), FastAPI will return a detailed error response indicating exactly which field failed validation. This saves you from writing manual validation code for every endpoint.

The Pydantic model is also used to generate the OpenAPI schema (Swagger UI). This means your API documentation will automatically show the expected JSON structure, including field types, required fields, and default values, making it easy for frontend developers to integrate with your API.

Code Breakdown

5
class Item(BaseModel): defines the schema for the request body.
7
description: Union[str, None] = None makes the field optional.
14
async def create_item(item: Item): tells FastAPI to parse the body into an Item object.
15
item.dict() converts the Pydantic model to a dictionary.