当前位置: 首页 > news >正文

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 Unionimport uvicorn
from fastapi import FastAPI
from pydantic import BaseModel, EmailStrapp = FastAPI()class UserIn(BaseModel):username: strpassword: stremail: EmailStr# Python 3.9 及以下:只能使用 Union[str, None]# Python 3.10+:两种语法都支持,推荐使用 str | Nonefull_name: str | None = None  # 等价full_name: Union[str, None] = Noneclass UserOut(BaseModel):  # 未包含密码username: stremail: EmailStrfull_name: Union[str, None] = None@app.post("/user", response_model=UserOut)
def create_user(user: UserIn):#  存到数据库return userif __name__ == '__main__':uvicorn.run("response_model:app", port=8001, reload=True)

 

接口文档

image

 

请求数据

image

 

响应

image

 

过滤response_model中的字段

示例

from typing import Listimport uvicorn
from fastapi import FastAPI
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: str | None = Noneprice: floattax: float = 12.5tags: 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)

 

没传的值展示默认值

接口文档

image

 

传了的值不会展示默认值

请求数据

image

 

 

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

image

 

请求数据

image

 

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

image

 

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]

  

请求数据

image

 

响应

image

 

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]

  

请求数据

image

 

响应

image

 

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]

 

请求数据

image

 

响应

image

 

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]

  

请求数据

image

 

响应

image

 

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]

 

请求数据

image

 

响应

image

 

http://www.jsqmd.com/news/304495/

相关文章:

  • 【双指针】判断是否为回文字符串
  • one_channel_hub 移植到CH584M MCU平台(移除WiFi/网络相关代码)
  • 9999999999
  • 关于Django项目的浏览器跨域问题
  • 9999999999999
  • 家政老板必读:避开小程序开发四大坑,打造高效赚钱的家政系统
  • JDK版本的区别
  • 嵌入式系统设计师软考个人笔记<3>
  • ADC相关
  • 目标检测数据集 - 野生动物检测数据集下载
  • 老年人评估项目开发记录3
  • 1.26假期记录
  • 2026年 铆接设备/铆接机厂家推荐排行榜:精选高效稳定铆接解决方案,助力精密制造升级
  • Claude Code Python 技能完整目录 - 2,847个顶级开发工具 - nano
  • 99999999999
  • =========
  • Sealos 私有化:离线环境部署踩坑实录
  • 2024年AI原生应用开源数据集推荐:高质量训练数据获取+处理全攻略
  • 别再问了,Sealos 私有化部署就这几步
  • 导师推荐!继续教育AI论文写作软件TOP9:9款测评帮你高效完成毕业论文
  • 2026年 铆钉机厂家推荐排行榜,双头铆钉机,气动铆钉机,全自动铆钉机,对敲铆钉设备,子母钉机,高效精准铆接设备源头精选
  • 大模型术语全解析:从LLM到Agent,小白必学指南
  • MCP:大模型界的Type-C标准,让你的工具一次编写到处运行(深度好文,值得收藏)
  • Ollama大模型开发实战:从基础到高级功能的全面指南
  • 从入门到精通:RAG生产级实战指南 | 大模型应用必备收藏
  • 大模型开发工程师年薪90万不是梦!零基础入门到高薪就业的完整攻略(附资料包)
  • Java毕设项目:基于springboot的机器人健康预警系统(源码+文档,讲解、调试运行,定制等)
  • 银源电力联系方式:企业信息查询与使用建议
  • 2026最新K歌电视品牌top5推荐!家庭娱乐影音设备企业及厂家权威榜单发布,沉浸式K歌体验
  • 【课程设计/毕业设计】基于JAVA+Vue+SpringBoot的个人健康管理系统健康档案、体检档案、健康咨询基于springboot的个人健康管理系统【附源码、数据库、万字文档】