FastAPI系列(12):响应模型参数

本系列汇总,请查看这里https://www.cnblogs.com/uncleyong/p/19503695

response_model

简介

FastAPI 提供了 response_model 参数,声明 return 响应体的模型

可以在任意的路径操作中使用response_model参数来声明用于响应的模型

response_model 是路径操作的参数,并不是路径函数的参数

复制代码
# 路径操作
@app.post("/items/", response_model=Item)
# 路径函数
async def create_item(item: Item):
    ...

FastAPI将使用response_model进行以下操作:

复制代码
- 将输出数据转换为response_model中声明的数据类型
- 验证数据结构和类型
- 将输出数据限制为该model定义的
- 添加到OpenAPI中
- 在自动文档系统中使用
示例

Pydantic 将某些功能设为可选依赖,避免不必要的包体积,'email' 是 Pydantic 提供的一个extras_require选项

pip install pydantic - 仅安装基础功能

pip install 'pydanticemail' - 安装基础 + 邮件验证功能

复制代码
from typing import Union

import uvicorn
from fastapi import FastAPI
from pydantic import BaseModel, EmailStr

app = FastAPI()


class UserIn(BaseModel):
    username: str
    password: str
    email: EmailStr
    # Python 3.9 及以下:只能使用 Union[str, None]
    # Python 3.10+:两种语法都支持,推荐使用 str | None
    full_name: str | None = None  # 等价full_name: Union[str, None] = None


class UserOut(BaseModel):  # 未包含密码
    username: str
    email: EmailStr
    full_name: Union[str, None] = None


@app.post("/user", response_model=UserOut)
def create_user(user: UserIn):
    #  存到数据库
    return user


if __name__ == '__main__':
    uvicorn.run("response_model:app", port=8001, reload=True)

接口文档

请求数据

响应

过滤response_model中的字段

示例
复制代码
from typing import List

import uvicorn
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str | None = None
    price: float
    tax: float = 12.5
    tags: List[str] = []


# 模拟数据库数据
items = {
    "foo": {"name": "Foo", "price": 50.2},
    "bar": {"name": "Bar", "description": "bar-description", "price": 100, "tax": 25.5},
    "baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
}


@app.get("/items/{item_id}", response_model=Item)
async def read_item(item_id: str):
    return items[item_id]




if __name__ == '__main__':
    uvicorn.run("response_model:app", port=8001, reload=True)
没传的值展示默认值

接口文档

传了的值不会展示默认值

请求数据

响应,没传的值展示默认值

请求数据

响应,传了的值不会展示默认值

response_model_exclude_unset:仅返回显式设定的值

示例

复制代码
@app.get("/items/{item_id}", response_model=Item, response_model_exclude_unset=True)
async def read_item(item_id: str):
    return items[item_id]

请求数据

响应

response_model_exclude_none:不返回是None的字段

示例

复制代码
@app.get("/items/{item_id}", response_model=Item, response_model_exclude_none=True)
async def read_item(item_id: str):
    return items[item_id]

请求数据

响应

response_model_exclude_defaults:不返回是默认值的字段

示例

复制代码
@app.get("/items/{item_id}", response_model=Item, response_model_exclude_defaults=True)
async def read_item(item_id: str):
    return items[item_id]

请求数据

响应

response_model_include:返回指定的字段

示例

复制代码
@app.get("/items/{item_id}", response_model=Item, response_model_include={"name", "price", "tax"})
async def read_item(item_id: str):
    return items[item_id]

请求数据

响应

response_model_exclude:不返回指定的字段

示例

复制代码
@app.get("/items/{item_id}", response_model=Item, response_model_exclude={"price", "tax"})
async def read_item(item_id: str):
    return items[item_id]

请求数据

响应

相关推荐
xieliyu.2 小时前
Java算法精讲:双指针(三)
java·开发语言·算法
love530love3 小时前
LiveTalking 数字人项目 Windows 部署完全指南(EPGF 架构)
人工智能·windows·python·架构·livetalking·epgf
遇事不決洛必達3 小时前
【Python基础】GIL 锁是什么及其对爬虫的影响
爬虫·python·线程·进程·gil锁
CryptoPP3 小时前
快速对接东京证券交易所API数据:实战指南与代码示例
开发语言·人工智能·windows·python·信息可视化·区块链
ZC跨境爬虫4 小时前
跟着 MDN 学JavaScript day_7:数学运算与逻辑判断实战测试
开发语言·前端·javascript·学习·ecmascript
探物 AI4 小时前
把 MambaOut 塞进 YOLOv11:会有什么样的反应
python·yolo·计算机视觉
如竟没有火炬4 小时前
最大矩阵——单调栈
数据结构·python·线性代数·算法·leetcode·矩阵
阳区欠5 小时前
【LangChain】LLM基础介绍
开发语言·python·langchain
Cosolar5 小时前
保姆级 CrewAI 教程:从零构建多智能体协作系统
人工智能·python·架构
Jinkxs5 小时前
Java 跨域14-Java 与区块链(Hyperledger)集成
java·开发语言·区块链