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 'pydantic[email]' - 安装基础 + 邮件验证功能

复制代码
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]

请求数据

响应

相关推荐
*Lisen1 小时前
从零手写 FlashAttention(PyTorch实现 + 原理推导)
人工智能·pytorch·python
昇腾CANN1 小时前
TileLang-Ascend 算子性能优化方法与实操
开发语言·javascript·性能优化·昇腾·cann
沐知全栈开发1 小时前
ionic 手势事件详解
开发语言
用户8356290780511 小时前
用 Python 轻松在 Excel 工作表中应用条件格式
后端·python
red1giant_star1 小时前
Python根据文件后缀统计文件大小、找出文件位置(仿Everything)
后端·python
雷欧力2 小时前
如何使用 Claude API?3 种接入方案实测,附完整代码(2026)
python·claude
lsx2024062 小时前
Bootstrap 按钮
开发语言
神仙别闹2 小时前
基于 Python 实现 BERT 的情感分析模型
开发语言·python·bert
禾叙_2 小时前
【langchain4j】结构化输出(六)
java·开发语言
NQBJT2 小时前
VS Code配置Python人工智能开发环境
开发语言·人工智能·vscode·python