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]

请求数据

响应

相关推荐
廋到被风吹走12 分钟前
【LangChain4j】特点功能及使用场景
后端·python·flask
Eward-an16 分钟前
LeetCode 239. 滑动窗口最大值(详细技术解析)
python·算法·leetcode
青槿吖1 小时前
第二篇:告别XML臃肿配置!Spring注解式IOC/DI保姆级教程,从入门到真香
xml·java·开发语言·数据库·后端·sql·spring
t198751281 小时前
TOA定位算法MATLAB实现(二维三维场景)
开发语言·算法·matlab
喵手1 小时前
Python爬虫实战:用代码守护地球,追踪WWF濒危物种保护动态!
爬虫·python·爬虫实战·濒危物种·零基础python爬虫教学·wwf·濒危物种保护动态追踪
梦想的旅途21 小时前
如何通过 QiWe API 实现企业微信主动发消息
开发语言·python
jllllyuz1 小时前
粒子群算法解决资源分配问题的MATLAB实现
开发语言·算法·matlab
喵手1 小时前
Python爬虫实战:自动化抓取 Pinterest 热门趋势与创意!
爬虫·python·爬虫实战·pinterest·零基础python爬虫教学·采集pinterest热门趋势·热门趋势预测
凌晨一点的秃头猪1 小时前
Python文件操作
开发语言·python
小张贼嚣张1 小时前
数据分析全流程实战:Python(Pandas/Matplotlib/Numpy)+ MySQL(附可下载数据源+多图形绘制)
python·数据分析·pandas