0
0
FastAPIframework~5 mins

Pydantic model definition in FastAPI

Choose your learning style9 modes available
Introduction

Pydantic models help you define clear and simple data shapes. They check data automatically so your app gets the right info.

When you want to make sure user input has the right form.
When you need to send data between parts of your app safely.
When you want to convert data from JSON to Python objects easily.
When you want to add simple rules to data like 'age must be a number'.
When building APIs that need clear data formats.
Syntax
FastAPI
from pydantic import BaseModel

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

Models inherit from BaseModel.

Fields are defined with type hints and optional default values.

Examples
A simple model with two fields: name and age.
FastAPI
from pydantic import BaseModel

class User(BaseModel):
    name: str
    age: int
Model with a default value for price.
FastAPI
from pydantic import BaseModel

class Product(BaseModel):
    id: int
    price: float = 0.0
Field that can be missing or None using Optional.
FastAPI
from pydantic import BaseModel
from typing import Optional

class Item(BaseModel):
    description: Optional[str] = None
Sample Program

This example shows how to define a Pydantic model and create an instance. It prints the whole object and each field.

FastAPI
from pydantic import BaseModel

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

# Create a person instance
person = Person(name="Alice", age=30)

print(person)
print(person.name)
print(person.age)
OutputSuccess
Important Notes

Pydantic automatically checks that data types match.

If data is wrong, it raises clear errors to help fix it.

Models can be nested to build complex data shapes.

Summary

Pydantic models define data shapes with types.

They validate data automatically.

Use them to keep your app data clean and safe.