Create the Expense Model
Exit

Create the Expense Model

Define a Pydantic model with field-level validation for expenses

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

BaseModel: the foundation for your data

Every Pydantic model inherits from BaseModel. This base class gives your class automatic validation, type conversion, and JSON serialization. You define fields as type-annotated class attributes, and BaseModel handles the rest.

Why field constraints matter

A basic Pydantic model checks data types, but it does not check values. Without constraints, your API will accept an expense with amount: -50 or description: "". Both pass type validation — one is a valid float, the other is a valid string — but neither makes sense as real data.

Pydantic's Field() function adds constraints directly to each field. The validation runs automatically when a request arrives. No extra code needed in your endpoint.

The constraints you will use

  • Field(min_length=1): rejects empty strings. A description of "" fails validation.
  • Field(gt=0): rejects zero and negative numbers. An amount of -5.0 or 0 fails validation.
  • Literal: restricts a field to a fixed set of values. A category of "food" passes; "snacks" fails.
  • Optional with a default: makes a field non-required. If the client omits date, Pydantic sets it to None instead of raising an error.

The Expense model

Your model will have four fields:

FieldTypeConstraint
descriptionstrAt least 1 character
amountfloatGreater than 0
categoryLiteralOne of: food, transport, entertainment, utilities, other
dateOptional[str]Defaults to None

Instructions

Build the Expense model below the app = FastAPI() line.

  1. Create a class named Expense that inherits from BaseModel.
  2. Add description as str with Field(min_length=1).
  3. Add amount as float with Field(gt=0).
  4. Add category as Literal["food", "transport", "entertainment", "utilities", "other"].
  5. Add date as Optional[str] with a default of None.