Middle
How does data validation and serialization work in FastAPI?
sobes.tech AI
Answer from AI
Validation and serialization of data in FastAPI are implemented using Pydantic models. When you declare request parameters, bodies, or responses through Pydantic classes, FastAPI automatically:
- Validates incoming data by types and constraints specified in the model.
- Converts (serializes) Python objects into JSON for responses.
- Handles validation errors and returns understandable messages to the client.
Example:
from fastapi import FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
class Item(BaseModel):
name: str = Field(..., min_length=3)
price: float
@app.post('/items/')
async def create_item(item: Item):
return item
Here, FastAPI will check that name is a string with at least 3 characters, and price is a floating-point number. If the data is invalid, the client will receive a 422 error with a description of the problem.