BaseModel, fields, and defaults
We wrote a StoryRequest earlier, but we barely scratched what Pydantic can do. Field is the hook for constraints, defaults, and descriptions that flow into the OpenAPI docs. Let us look at the real model the workshop uses, and then pull it apart.
The Pydantic validation pipeline
Raw JSON in, typed model out. Same shape on the way back with response_model.
from pydantic import BaseModel, Field
class StoryRequest(BaseModel):
"""Defines what data we need to generate a story."""
character_name: str = Field(
...,
min_length=1,
max_length=50,
description="The name of the story's main character"
)
character_age: int = Field(
...,
ge=1,
le=18,
description="Age of the character (1-18 years)"
)
story_theme: str = Field(
...,
min_length=1,
max_length=100,
description="The theme or topic of the story (e.g., 'friendship', 'adventure')"
)
story_length: str = Field(
...,
description="Desired length: 'short', 'medium', or 'long'"
)Every Field(...) marks a required parameter. ge, le, min_length, and max_length become Pydantic constraints, which FastAPI surfaces in the 422 error and in /docs.
To make a field optional with a default, you replace the ellipsis with a real value. For example, story_length: str = "medium" makes the field optional and the default shows up in the OpenAPI docs. If you want both a default and validation rules, use Field("medium", description="...").
Quiz: Quiz
Loading practice…