Nested models and Optional fields

Real payloads are not flat. A story request might include an author dict, a metadata object, or a list of tags. Pydantic handles this by letting one BaseModel contain another. And when a field can legitimately be absent, you mark it Optional instead of making the whole request fail.

models.py
python
from pydantic import BaseModel, HttpUrl
from typing import Optional

class ProcessingStatus(BaseModel):
    """Status of URL processing."""
    url: str
    status: str  # "processing", "completed", "error"
    progress: int  # 0-100
    message: str
    documents_count: int = 0
    error: Optional[str] = None


class URLRequest(BaseModel):
    """Request to add and process a URL."""
    url: HttpUrl
    chunk_size: int = 500
    chunk_overlap: int = 50

Optional[str] = None means the field may be missing. HttpUrl is a Pydantic-supplied type that validates URL shape for free.

Optional[str] is shorthand for Union[str, None]. It tells the type checker that None is valid. You usually pair it with a default of None so the field is actually optional. Plain str with a default of None is a lie to the type checker, since None is not a string. Be honest to your types and use Optional when the value can be missing.

Checkpoint: Pydantic contracts checkpoint

Loading practice…