Request-body schemas
Define JSON payloads for POST, PUT, PATCH, or similar operations.
FastAPI · Class
BaseModel is the Pydantic superclass for defining typed data models in FastAPI. Subclass it to describe request bodies with standard Python annotations, enabling structured input handling and automatic API schema generation.
BaseModel is a Pydantic base class used to define typed data models. In FastAPI, a path-operation parameter annotated with such a model is interpreted as a request body, while the model's fields provide validation and schema information.
class ModelName(BaseModel):
field_name: field_typefrom fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str | None = None
price: float
@app.post("/items/")
async def create_item(item: Item) -> Item:
return item
The model declares the request fields and their Python types; FastAPI uses the model parameter as the request body and returns the validated model.
Define JSON payloads for POST, PUT, PATCH, or similar operations.
Share one typed structure across multiple endpoint declarations.
Expose nested objects with explicit field types.
A class inheriting from Pydantic's BaseModel defines the fields of a data model using standard Python types. FastAPI uses that model to interpret a path-operation parameter as request-body data and to generate its schema.
Follow-up: How can the same model participate in response handling? Annotate the return type or use response_model; FastAPI can then validate, document, serialize, and filter the returned data.
Each model attribute is declared with a Python type, such as str or float, and optional fields can have a default of None. FastAPI uses those declarations for request-body structure and automatic documentation.
Follow-up: How would you represent nested JSON? Define a field whose type is another Pydantic model; FastAPI supports arbitrarily deeply nested models.
A parameter annotated with a Pydantic model is taken from the request body, while a parameter whose name matches a path placeholder is taken from the path. Body, path, and query parameters can be declared together.
Follow-up: Can model fields come from forms instead? Yes: declare the model with Form and FastAPI extracts each field from submitted form data.
Pydantic modelsRequest BodyResponse Model - Return TypeNested ModelsForm Models