MongoDB with FastAPI & Python

Lesson 3 of 6

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 clear 422 error automatically, your code never even runs.
  • done: bool = False gives that field a default, so callers don't have to include it.
  • TaskOut reuses Task and adds an id field, 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.

📝 Pydantic Quiz

Passing score: 70%
  1. 1.What happens if a request body is missing a required field on a Pydantic model?

  2. 2.Pydantic model classes inherit from ____.

  3. 3.Giving a field a default value, like `done: bool = False`, makes it optional in requests.