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

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

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

是否遇到过这些问题?

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