• FastAPI 响应模型:Pydantic 的数据验证与转换,一篇吃透!

FastAPI 响应模型:Pydantic 的数据验证与转换,一篇吃透!

2025-04-27 10:41:11 栏目:宝塔面板 171 阅读

是否遇到过这些问题?

  • 数据库返回字段太多,前端只要几个?
  • 接口文档不一致,测试老是报错?
  • ORM 对象直接返回,总是类型错误?

快用 FastAPI 的响应模型(response_model)+ Pydantic,自动校验、转换、过滤、文档全搞定!

1. 什么是响应模型?

响应模型用于定义接口的返回结构。FastAPI 会根据响应模型:

  • 自动校验字段类型
  • 自动过滤多余字段
  • 自动转换格式
  • 自动生成文档(OpenAPI)

2. 快速上手:定义响应结构

from pydantic import BaseModel

class UserOut(BaseModel):
    id: int
    name: str
    email: str

在接口中使用:

from fastapi import FastAPI

app = FastAPI()

@app.get("/users/{user_id}", response_model=UserOut)
def get_user(user_id: int):
    return {
        "id": user_id,
        "name": "Alice",
        "email": "alice@example.com",
        "is_admin": True  # 会自动被过滤掉
    }

最终返回只包含指定字段:

{
  "id": 1,
  "name": "Alice",
  "email": "alice@example.com"
}

3. 支持嵌套模型和列表模型

class Address(BaseModel):
    city: str
    country: str

class UserOut(BaseModel):
    id: int
    name: str
    address: Address

列表结构也支持:

@app.get("/users/", response_model=list[UserOut])
def get_users():
    return [...]

4. ORM 模式(必须开启):与数据库模型打通

如果你使用 SQLAlchemy、Tortoise ORM 等,接口函数中返回的是 ORM 实例而不是字典,就必须开启 “ORM 模式”。

为什么要开启?

因为 ORM 对象不是标准字典,Pydantic 默认不能识别对象的属性,需要开启专用模式:

(1) Pydantic v1 的写法

class UserOut(BaseModel):
    id: int
    name: str

    class Config:
        orm_mode = True

FastAPI 会自动调用 obj.__dict__ 或属性方法,提取字段。

(2) Pydantic v2 的写法(推荐)

class UserOut(BaseModel):
    id: int
    name: str

    model_config = {
        "from_attributes": True  # 替代 orm_mode
    }

from_attributes=True 更加清晰地表明“这个模型的字段可以从属性中提取”。

(3) 搭配 SQLAlchemy 使用示例

from sqlalchemy.orm import declarative_base
from sqlalchemy import Column, Integer, String

Base = declarative_base()

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True)
    name = Column(String)

# 响应模型
class UserOut(BaseModel):
    id: int
    name: str

    model_config = {
        "from_attributes": True
    }

@app.get("/users/{id}", response_model=UserOut)
def get_user(id: int, db: Session = Depends(get_db)):
    return db.query(User).get(id)

(4) 搭配 Tortoise ORM 使用示例

from tortoise.models import Model
from tortoise import fields

class User(Model):
    id = fields.IntField(pk=True)
    name = fields.CharField(max_length=50)

class UserOut(BaseModel):
    id: int
    name: str

    model_config = {
        "from_attributes": True
    }

@app.get("/users/{id}", response_model=UserOut)
async def get_user(id: int):
    user = await User.get(id=id)
    return user

 5. 响应字段别名与描述(自动生成文档)

from pydantic import Field

class UserOut(BaseModel):
    id: int
    name: str = Field(..., alias="username", description="用户名")

返回结构变为:

{
  "id": 1,
  "username": "Alice"
}

在 Swagger 文档中也能自动显示字段描述!

6. Pydantic v1 vs v2 对比

功能点

v1

v2(推荐)

底层实现

Python 实现

Rust 实现(pydantic-core)

性能

一般

本文地址:https://www.yitenyun.com/106.html

搜索文章

Tags

数据库 API FastAPI Calcite 电商系统 MySQL Web 应用 异步数据库 数据同步 ACK 双主架构 循环复制 TIME_WAIT 运维 负载均衡 服务器 管理口 JumpServer SSL 堡垒机 跳板机 HTTPS HexHub Docker 服务器性能 JumpServer安装 堡垒机安装 Linux安装JumpServer SQL 查询 Deepseek 宝塔面板 Linux宝塔 生命周期 esxi esxi6 root密码不对 无法登录 web无法登录 锁机制 序列 核心机制 Windows Windows server net3.5 .NET 安装出错 HTTPS加密 行业 趋势 Windows宝塔 Mysql重置密码 开源 PostgreSQL 存储引擎 宝塔面板打不开 宝塔面板无法访问 查看硬件 Linux查看硬件 Linux查看CPU Linux查看内存 机器学习 Redis Undo Log 机制 Oracle 处理机制 Spring 动态查询 无法访问宝塔面板 响应模型 InnoDB 数据库锁 优化 万能公式 连接控制 异步化 监控 Serverless 无服务器 语言 ES 协同 group by 索引 openHalo 工具 Postgres OTel Iceberg 高可用 技术 分页查询 缓存方案 缓存架构 缓存穿透 scp Linux的scp怎么用 scp上传 scp下载 scp命令 SVM Embedding 存储 GreatSQL 连接数 数据 主库 国产数据库 R edis 线程 日志文件 MIXED 3 Linux 安全 SQLite-Web SQLite 数据库管理工具 加密 场景 R2DBC Netstat Linux 服务器 端口 启动故障 ​Redis 推荐模型 Recursive 防火墙 黑客 云原生 OB 单机版 自定义序列化 RocketMQ 长轮询 配置 SQLark 向量数据库 大模型 共享锁 AI 助手 Canal PG DBA Hash 字段 不宕机 Rsync 信息化 智能运维 Python 向量库 Milvus Ftp 磁盘架构 电商 系统 IT运维 分库 分表 架构 业务 数据分类 同城 双活 修改DNS Centos7如何修改DNS 语句 聚簇 非聚簇 PostGIS 频繁 Codis 传统数据库 向量化 线上 库存 预扣 filelock redo log 重做日志 流量 MongoDB MCP 开放协议 • 索引 • 数据库 MVCC MySQL 9.3 mini-redis INCR指令 缓存 数据类型 sftp 服务器 参数 数据结构 人工智能 推荐系统 Web 接口 开发 失效 ZODB 工具链 分布式架构 分布式锁​ 千万级 大表 Redisson 锁芯 Doris SeaTunnel EasyExcel MySQL8 聚簇索引 非聚簇索引 高效统计 今天这篇文章就跟大家 prometheus Alert 数据备份 窗口 函数 虚拟服务器 虚拟机 内存 主从复制 代理 INSERT 崖山 新版本 事务 Java COMPACT 容器 发件箱模式 分页 SSH 网络架构 网络配置 引擎 性能 MGR 分布式集群 Web 数据脱敏 加密算法 RDB AOF 核心架构 订阅机制 速度 服务器中毒 网络故障 QPS 高并发 Redis 8.0 数据集成工具 读写 Go 数据库迁移 自动重启 B+Tree ID 字段 播客 分布式 集中式 数据页 Redka 容器化 OAuth2 Token 模型 StarRocks 数据仓库 排行榜 排序 微软 SQL Server AI功能 SpringAI Entity 池化技术 连接池 Caffeine CP 事务隔离 Valkey Valkey8.0 DBMS 管理系统 原子性 关系数据库 JOIN 数据字典 兼容性 Weaviate 网络 部署 LRU 业务场景 Testcloud 云端自动化 dbt 数据转换工具 分页方案 排版 1 ReadView 事务同步 Pottery 优化器 sqlmock 日志 意向锁 记录锁 AIOPS 悲观锁 乐观锁 UUID ID 单点故障 单线程 Pump UUIDv7 主键 仪表盘 InfluxDB Order 编程 RAG HelixDB 对象 Crash 代码 Ansible 分布式锁 Zookeeper 产业链 IT 字典 双引擎 恢复数据 订单 LLM List 类型 拦截器 动态代理 线程安全 国产 用户 慢SQL优化 表空间 count(*) count(主键) 行数 解锁 调优 快照读 当前读 视图 RR 互联网 GitHub Git 神经系统 Next-Key 矢量存储 数据库类型 AI代理 CAS 查询规划 算法 技巧 多线程 闪回 并发控制 恢复机制