Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pydantic Schema — Data Validation and Serialization

Pydantic Schema — Data Validation and Serialization

In this chapter you'll learn Pydantic Schema and understand its separation of responsibilities from ORM models—FastAPI's most core feature.


Why do you need a Schema?

ORM models (models.py) define the database structure, but can't be used directly for API request/response validation.

Reason: ORM models contain database-specific logic (such as relationship), and you don't want to expose all fields to the API.

A Pydantic Schema is a pure data class dedicated to API input/output validation and serialization.

The relationship among these three:



客户端 → [Pydantic Schema 校验] → 路由函数 → [ORM 模型] → 数据库

客户端 ← [Pydantic Schema 序列化] ← 路由函数 ← [ORM 模型] ← 数据库


Pydantic Schema basics

Pydantic V2 is FastAPI's data engine, defining data structures through type hints.

Example

from

pydantic

import

BaseModel

,

ConfigDict

class

ItemCreate

(

BaseModel

)

:

   

"""Schema for creation requests"""

    name:

str

    price:

float

                     

Automatic type validation

    is_offer:

bool

=

False

           

With default values (optional fields)

class

ItemResponse

(

BaseModel

)

:

   

"""Response Schema"""

   

id

:

int

    name:

str

    price:

float

   

V2 syntax: enable ORM mode to allow direct conversion from ORM objects

    model_config

=

ConfigDict

(

from_attributes

=

True

)


Define the blog's Schemas

Example

File path: schemas.py

from

pydantic

import

BaseModel

,

ConfigDict

from

datetime

import

datetime

from

typing

import

Optional

====== Category Schema ======

class

CategoryBase

(

BaseModel

)

:

    name:

str

    slug:

str

class

CategoryResponse

(

CategoryBase

)

:

   

id

:

int

    model_config

=

ConfigDict

(

from_attributes

=

True

)

====== Post Schema ======

class

PostBase

(

BaseModel

)

:

    title:

str

    slug:

str

    summary: Optional

[

str

]

=

None

     

Optional = can be None

    content:

str

    category_id:

int

class

PostCreate

(

PostBase

)

:

   

"""Request-body Schema for creating a post"""

   

pass

                             

Directly inherits PostBase, with identical fields

class

PostUpdate

(

BaseModel

)

:

   

"""Update a post (all fields optional)"""

    title: Optional

[

str

]

=

None

    slug: Optional

[

str

]

=

None

    summary: Optional

[

str

]

=

None

    content: Optional

[

str

]

=

None

    category_id: Optional

[

int

]

=

None

class

PostResponse

(

PostBase

)

:

   

"""Response Schema returned to the client"""

   

id

:

int

    created_at:

datetime

    updated_at:

datetime

    category: CategoryResponse        

Nested Schema: return category information

    model_config

=

ConfigDict

(

from_attributes

=

True

)

   

from_attributes=True tells Pydantic that this Schema can be created from an ORM object

In Pydantic V2,model_config = ConfigDict(from_attributes=True) replaces V1's class Config: orm_mode = True. This config lets you build a Pydantic Schema directly from a SQLAlchemy ORM object:PostResponse.model_validate(post_orm_obj)。


Using Schemas in routes

Example

File path: routers/posts.py (example of creating a POST route)

from

fastapi

import

APIRouter

,

Depends

,

HTTPException

from

sqlalchemy.

orm

import

Session

from

database

import

get_db

from

models

import

Post

from

schemas

import

PostCreate

,

PostResponse

router

=

APIRouter

(

prefix

=

"/posts"

,

tags

=

[

"Article"

]

)

After declaring response_model=PostResponse:

1. FastAPI automatically converts ORM objects to Schemas (serialization)

2. The API docs automatically show the response structure

@

router.

post

(

"/"

,

response_model

=

PostResponse

,

status_code

=

201

)

def

create_post

(

post_data: PostCreate

,

db: Session

=

Depends

(

get_db

)

)

:

   

"""
    Create a new post
    - post_data: the request body, automatically validated by FastAPI against the PostCreate Schema
    - db: the database session injected via Depends(get_db)
    """

    post

=

Post

(

**post_data.

model_dump

(

)

)

 

model_dump() converts the Schema to a dictionary

    db.

add

(

post

)

    db.

commit

(

)

    db.

refresh

(

post

)

                     

Refresh to get the database auto-increment ID

   

return

post                            

FastAPI automatically serializes with PostResponse

response_model is one of FastAPI's strongest features. Once declared, FastAPI will: 1. automatically filter out ORM fields not declared in the Schema; 2. convert types like datetime to JSON strings; 3. generate accurate OpenAPI docs.


ORM model vs Pydantic Schema comparison

Aspect SQLAlchemy ORM model Pydantic Schema
Definition location models.py schemas.py
base class Base (DeclarativeBase) BaseModel (Pydantic)
Responsibility Defines database table structure and relationships Defines API input/output formats and validation rules
Relationship with the database Directly maps database tables Doesn't care about the database, only the API contract
Field declarations Column(Integer, ...) Python type hints: int, str
Serialization Can't be converted to JSON directly Built-in .model_dump() and JSON serialization
Conversion direction ORM → Schema:model_validate(obj) Schema → ORM:Model(**schema.model_dump())

Chapter Summary

In this chapter you mastered FastAPI's most core Pydantic Schema: BaseModel defines request/response Schemas, from_attributes=True enables ORM mode, response_model automatically serializes ORM objects, and the principle of separating Schema and ORM model responsibilities.

This is the essence of FastAPI's type-driven architecture—define the data shape first, and routes and docs are generated automatically.