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.0or0fails validation.Literal: restricts a field to a fixed set of values. A category of"food"passes;"snacks"fails.Optionalwith a default: makes a field non-required. If the client omitsdate, Pydantic sets it toNoneinstead of raising an error.
The Expense model
Your model will have four fields:
| Field | Type | Constraint |
|---|---|---|
description | str | At least 1 character |
amount | float | Greater than 0 |
category | Literal | One of: food, transport, entertainment, utilities, other |
date | Optional[str] | Defaults to None |
Instructions
Build the Expense model below the app = FastAPI() line.
- Create a class named
Expensethat inherits fromBaseModel. - Add
descriptionasstrwithField(min_length=1). - Add
amountasfloatwithField(gt=0). - Add
categoryasLiteral["food", "transport", "entertainment", "utilities", "other"]. - Add
dateasOptional[str]with a default ofNone.
from fastapi import FastAPI from pydantic import BaseModel, Field from typing import Literal, Optional app = FastAPI() # Step 1: Create a class named Expense that inherits from BaseModel # Step 2: Add description as str with Field(min_length=1) # Step 3: Add amount as float with Field(gt=0) # Step 4: Add category as Literal["food", "transport", "entertainment", "utilities", "other"] # Step 5: Add date as Optional[str] with a default of None
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding