0
0
FastAPIframework~5 mins

Pydantic model basics in FastAPI

Choose your learning style9 modes available
Introduction

Pydantic models help you check and organize data easily. They make sure your data is correct before using it.

When you want to check user input in a web app.
When you need to convert data from JSON to Python objects.
When you want to make sure data has the right types like numbers or text.
When you want to keep your code clean and easy to understand.
When you want automatic error messages if data is wrong.
Syntax
FastAPI
from pydantic import BaseModel

class ModelName(BaseModel):
    field_name: field_type
    another_field: another_type

Models inherit from BaseModel.

Each field has a name and a type, like str or int.

Examples
This model checks that name is text and age is a number.
FastAPI
from pydantic import BaseModel

class User(BaseModel):
    name: str
    age: int
This model has a product with an ID number, a price with decimals, and a true/false stock status.
FastAPI
from pydantic import BaseModel

class Product(BaseModel):
    id: int
    price: float
    in_stock: bool
Sample Program

This example shows how to create a Person model. It prints the valid person data. Then it tries to create a person with wrong age type and prints the error.

FastAPI
from pydantic import BaseModel, ValidationError

class Person(BaseModel):
    name: str
    age: int

# Correct data
person1 = Person(name="Alice", age=30)
print(person1)

# Incorrect data example
try:
    person2 = Person(name="Bob", age="thirty")
except ValidationError as e:
    print(e)
OutputSuccess
Important Notes

Pydantic automatically converts data types when possible, like strings to numbers.

If data is wrong, Pydantic shows clear error messages to help fix it.

You can add default values by writing field_name: type = default_value.

Summary

Pydantic models check and organize data with simple classes.

They help catch errors early by validating data types.

Use them to keep your app data clean and easy to work with.