FastAPI之响应模型

前言

响应模型我认为最主要的作用就是在自动化文档的显示时,可以直接给查看文档的小伙伴显示返回的数据格式。对于后端开发的伙伴来说,其编码的实际意义不大,但是为了可以不用再额外的提供文档,我们只需要添加一个 response_model=xxx,还是很爽的

示例

没有响应模型

from fastapi import FastAPI, Header
from pydantic import BaseModel

app = FastAPI()


class Resp(BaseModel):
    code: int
    msg: str
    data: list


@app.get("/")
async def read_root():
    return Resp(code=0, msg='success', data=[{
   "name": "Python"}, {
   "name": "Java"}])

效果
在这里插入图片描述

此时我们的文档只可以看到返回的是字符串,这和没写文档一样,现在尝试加上response_model

添加响应模型

from fastapi import FastAPI, Header
from pydantic import BaseModel

app = FastAPI()


class User(BaseModel):
    id: int
    name: str


class Resp(BaseModel):
    code: int
    msg: str
    data: list[User]


@app.get("/",response_model=Resp)
async def read_root():
    return Resp(
        code=0,
        msg='success',
        data=[
            User(id=1, name='test'),
            User(id=2, name='test2')
        ]
    )

打开自动化文档,显示效果如下:
在这里插入图片描述
此时我们需要格外注意,我们规定了返回的是Resp模型,这个模型中有code、msg、data三个字段,如果我们返回的数据缺少了一个字段,那么,请求接口的时候,就会报错,比如我们把msg='success'注释掉,再次请求,将会有错误产生:
在这里插入图片描述

进阶使用:response_model_exclude_unset

如果你不想在响应模型中包括默认值未被修改的字段,你可以使用response_model_exclude_unset参数。

@app.post("/items/exclude_unset", response_model=Item, response_model_exclude_unset=True)
async def create_item_exclude_unset(item: Item):
    return item

在这个例子中,如果你提交了一个不包含descriptiontax字段的请求(因为它们有默认值且未修改),响应将不会包含这些字段。

response_model_includeresponse_model_exclude

response_model_includeresponse_model_exclude参数让你可以更精细地控制响应数据。response_model_include指定应该包含的字段,而response_model_exclude指定应该排除的字段。

只包含特定字段

@app.post("/items/include", response_model=Item, response_model_include={
   "name", "price"})
async def create_item_include(item: Item):
    return item

在这个例子中,响应只会包含nameprice字段,即使其他字段在请求体中被定义。

排除特定字段

@app.post("/items/exclude", response_model=Item, response_model_exclude={
   "tax"})
async def create_item_exclude(item: Item):
    return item

在这个例子中,返回的响应将不包含tax字段。

实操演示

为了更好地理解这些概念,我们实现一个实例,其中我们创建一个简单的商品入库API,并在不同的端点展示response_model的不同用法。

from typing import Set

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None
    tags: Set[str] = set()

# 默认的response_model使用
@app.post("/items/", response_model=Item)
async def create_item(item: Item):
    return item

# 排除未设置的字段
@app.post("/items/exclude_unset", response_model=Item, response_model_exclude_unset=True)
async def create_item_exclude_unset(item: Item):
    # 模拟item创建
    return item

# 只包含特定字段
@app.post("/items/include_only", response_model=Item, response_model_include=["name", "price"])
async def create_item_include_only(item: Item):
    # 模拟item创建
    return item

# 排除特定字段
@app.post("/items/exclude_some", response_model=Item, response_model_exclude=["tax"])
async def create_item_exclude_some(item: Item):
    # 模拟item创建
    return item

当你运行这个FastAPI应用并向这些端点发送请求时,你应该会注意到,每个端点都根据设定的参数,返回不同结构的JSON响应。

记得要调试和测试每个端点,确保它的行为符合预期,这样你就能更好地理解response_model的这些高级特性如何帮助你控制API的响应格式。

结论

response_model和其他相关参数提供了强大的方式来控制你的API响应。通过选择性地包括、排除或者隐藏响应数据的特定字段,你可以创建更加灵活和高效的API端点。这些特性尤其在处理大型数据模型或希望限制客户端收到数据的场景下非常有用。通过本教程的介绍,希望你能在自己的FastAPI项目中更加自如地使用这些高级功能。

相关推荐

  1. 写在FastAPI旅之前

    2023-12-13 02:54:02       36 阅读
  2. SpringMVC处理响应

    2023-12-13 02:54:02       30 阅读
  3. react响应事件

    2023-12-13 02:54:02       10 阅读
  4. fastapi数据库连接池的模版

    2023-12-13 02:54:02       14 阅读
  5. FastAPI Web框架教程 第11章 请求响应的进阶用法

    2023-12-13 02:54:02       14 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-13 02:54:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-13 02:54:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-13 02:54:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-13 02:54:02       18 阅读

热门阅读

  1. 网络编程发送接受多案例

    2023-12-13 02:54:02       39 阅读
  2. C++学习笔记(十四)

    2023-12-13 02:54:02       35 阅读
  3. python 中Windows编程一些心得

    2023-12-13 02:54:02       44 阅读
  4. 【算法集训】基础数据结构:四、栈

    2023-12-13 02:54:02       44 阅读
  5. linux链表应用2

    2023-12-13 02:54:02       40 阅读
  6. 2.2运行时数据区域----2.2.3本地方法栈

    2023-12-13 02:54:02       36 阅读
  7. Linux中的iptables

    2023-12-13 02:54:02       32 阅读
  8. vue:this.reload()跟this.$router.replace的区别

    2023-12-13 02:54:02       44 阅读
  9. C语言L / 数据在内存中的存储

    2023-12-13 02:54:02       31 阅读
  10. c# 十进制整数格式化-(占位符,补齐)

    2023-12-13 02:54:02       47 阅读
  11. 申论笔记(思路技巧)

    2023-12-13 02:54:02       37 阅读
  12. 分享一个Pinia存储的数据持久化插件

    2023-12-13 02:54:02       37 阅读