Defining Data Models with Pydantic
FastAPI uses Pydantic models to describe the shape of your data, then automatically validates incoming requests against them.
from pydantic import BaseModel
from typing import Optional
class Task(BaseModel):
title: str
done: bool = False
tags: list[str] = []
class TaskOut(Task):
id: str
What this buys you
- If a request is missing
title, or sends the wrong type, FastAPI rejects it with a clear422error automatically, your code never even runs. done: bool = Falsegives that field a default, so callers don't have to include it.TaskOutreusesTaskand adds anidfield, useful for responses (which include a database-assigned id) versus requests (which don't have one yet).
TIP
Think of Pydantic models as the FastAPI equivalent of a SQL table schema, they're where you write down the "shape" your data must have.