Sending Data: Request Body and Pydantic
Sending Data: Request Body and Pydantic
Section titled “Sending Data: Request Body and Pydantic”Receiving JSON Data
Section titled “Receiving JSON Data”When you need to send data from a client (like a browser) to your API, you typically send it as a Request Body. The most common format for this is JSON. To declare a request body in FastAPI, you use Pydantic models.
Defining Pydantic Models
Section titled “Defining Pydantic Models”Pydantic is a library that allows you to define the “shape” or schema of your data using Python classes. You define a class that inherits from BaseModel, and declare attributes with standard Python types.
from typing import Unionfrom fastapi import FastAPIfrom pydantic import BaseModel
class Item(BaseModel): name: str description: Union[str, None] = None price: float is_offer: bool = False
app = FastAPI()In this Item model:
nameandpriceare required (no default values).descriptionis optional and defaults toNone.is_offeris optional and defaults toFalse.
Using the Model in an Endpoint
Section titled “Using the Model in an Endpoint”To receive this data in your API, declare it as a parameter in your path operation function and use the Pydantic model class as the type hint.
@app.post("/items/")def create_item(item: Item): # FastAPI converts the JSON body into an 'item' object return itemWhen a user sends a POST request to /items/, FastAPI will automatically:
- Read the body as JSON.
- Convert the corresponding types (if needed).
- Validate the data against the
Itemmodel. - Give you the data in the function as the
itemparameter. You even get code completion for attributes likeitem.nameinside your function!
Automatic Validation and Error Messages
Section titled “Automatic Validation and Error Messages”If the client sends invalid data—for example, sending a string “twenty” for the price field (which expects a float)—FastAPI will automatically return a 422 Unprocessable Entity error.
The response body will contain a clear JSON indication of exactly what went wrong and where, helping the client fix their request without you needing to write custom validation logic.