fastapi 请求体 - 多个参数 / 字段Field / 嵌套模型

简介: fastapi 请求体 - 多个参数 / 字段Field / 嵌套模型

文章目录

1. 混合使用 Path、Query 和请求体参数

2. 多个请求体参数

3. 请求体中的单一值

4. 多个请求体参数和查询参数

5. 嵌入单个请求体参数

6. 字段

7. 嵌套模型

7.1 List 字段

7.2 子模型作为类型

8. 特殊类型校验

9. 带有一组子模型的属性

10. 任意 dict 构成的请求体


1. 混合使用 Path、Query 和请求体参数

from fastapi import FastAPI, Path
from typing import Optional
from pydantic import BaseModel
app = FastAPI()
class Item1(BaseModel):
    name: str
    price: float
    description: Optional[str] = None
    tax: Optional[float]
@app.put("/items/{item_id}")
async def update_item(
    *,
    item_id: int = Path(..., title="id of item to get", ge=0, le=1000),
    q: Optional[str] = None,
    item: Optional[Item1] = None,
):
    res = {"item_id": item_id}
    if q:
        res.update({"q": q})
    if item:
        res.update({"item": item})
    return res

image.pngimage.png


2. 多个请求体参数


from pydantic import BaseModel
class Item(BaseModel):
    name: str
    price: float
    description: Optional[str] = None
    tax: Optional[float]
class User(BaseModel):
    username: str
    full_name: Optional[str] = None
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item, user: User):
    res = {"item_id" : item_id, "item" : item, "user": user}
    return res

image.pngimage.png


3. 请求体中的单一值

  • 传参时,varname : type = Body(...),如果不这么写,会被作为查询参数 ?varname=xxx
from fastapi import Body
class Item(BaseModel):
    name: str
    price: float
    description: Optional[str] = None
    tax: Optional[float]
class User(BaseModel):
    username: str
    full_name: Optional[str] = None
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item, user: User, importance : int = Body(...)):
    res = {"item_id" : item_id, "item" : item, "user": user}
    return res

image.pngimage.png


4. 多个请求体参数和查询参数


由于默认情况下单一值被解释为查询参数,因此你不必显式地添加 Query,你可以仅执行操作:q: str = None


5. 嵌入单个请求体参数


如果你只有一个请求体参数

@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
    res = {"item_id" : item_id, "item" : item}
    return res

image.png

如果你想写成 带 key 的 json 形式,添加一个传入参数 embed,item: Item = Body(..., embed=True)

image.pngimage.png

6. 字段


可以使用 PydanticFieldPydantic 模型内部声明校验和元数据

from fastapi import FastAPI, Path, Body
from typing import Optional
from pydantic import BaseModel, Field
app = FastAPI()
class Item(BaseModel):
    name: str
    price: float = Field(..., gt=0, description="price must be greater than 0")
    description: Optional[str] = Field(None, title="description of item", max_length=30)
    tax: Optional[float] = None
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item = Body(..., embed=True)):
    res = {"item_id" : item_id, "item" : item}
    return res


Field 的工作方式和 Query、Path 和 Body 相同,包括它们的参数等等也完全相同

  • 注意,from pydantic import Field

7. 嵌套模型


7.1 List 字段


将一个属性定义为拥有子元素的类型,如 list

class Item(BaseModel):
    name: str
    price: float = Field(..., gt=0, description="price must be greater than 0")
    description: Optional[str] = Field(None, title="description of item", max_length=30)
    tax: Optional[float] = None
    tags: list = [] # 没有声明元素类型
  • 具有子类型的 List,from typing import List
tags: List[str] = []


7.2 子模型作为类型

from fastapi import FastAPI, Path, Body
from typing import Optional, List, Set
from pydantic import BaseModel, Field
app = FastAPI()
class Image(BaseModel):
    url:str
    name: str
class Item(BaseModel):
    name: str
    price: float = Field(..., gt=0, description="price must be greater than 0")
    description: Optional[str] = Field(None, title="description of item", max_length=30)
    tax: Optional[float] = None
    tags: Set[str] = []
    image: Optional[Image] = None
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item = Body(..., embed=True)):
    res = {"item_id" : item_id, "item" : item}
    return res

image.pngimage.png


8. 特殊类型校验


  • HttpUrl,检查是不是有效的 URL
from pydantic import BaseModel, Field, HttpUrl
app = FastAPI()
class Image(BaseModel):
    url: HttpUrl
    name: str


则上面的输入应改的地方 "url":"http://www.michael.com",否则不是有效的 URL


9. 带有一组子模型的属性


  • 更改为 image: Optional[List[Image]] = None
    输入需要改为
  • image.pngimage.png

10. 任意 dict 构成的请求体

from typing import Optional, List, Set, Dict
@app.post("/index-weights/")
async def create_index_weights(weights: Dict[int, float]): 
                # key 为 int, value 为浮点
    return weights

image.png

相关文章
|
6天前
|
JSON API 持续交付
逐步指南:使用FastAPI部署YOLO模型的步骤
逐步指南:使用FastAPI部署YOLO模型的步骤
|
9月前
|
数据采集 JSON JavaScript
全面拥抱FastApi —三大参数及验证
全面拥抱FastApi —三大参数及验证
|
6天前
|
JSON API 数据安全/隐私保护
如何使用Fastapi上传文件?先从请求体数据讲起
如何使用Fastapi上传文件?先从请求体数据讲起
|
6天前
|
Python
Fastapi进阶用法,路径参数,路由分发,查询参数等详解
Fastapi进阶用法,路径参数,路由分发,查询参数等详解
|
6天前
|
IDE 测试技术 开发工具
FastAPI 并发请求解析:提高性能的重要特性
在当今的数字化世界中,网络用户对于高速响应和持续连接的诉求日益显著。这促使了基于 Python 构建的 FastAPI 框架受到广泛关注,它不仅现代化且效率极高,而且简化了并行请求的处理。本篇文章旨在探讨 FastAPI 如何处理这类请求,并对应用实例进行实际编码展示。
|
7月前
|
JSON Kubernetes API
使用FastAPI部署Ultralytics YOLOv5模型
YOLO是You Only Look Once(你只看一次)的缩写,它具有识别图像中的物体的非凡能力,在日常应用中会经常被使用。所以在本文中,我们将介绍如何使用FastAPI的集成YOLOv5,这样我们可以将YOLOv5做为API对外提供服务。
170 5
|
9月前
|
JSON NoSQL API
全面拥抱 FastApi — 响应模型
全面拥抱 FastApi — 响应模型
|
12月前
|
网络安全 Windows
基于fastapi实现6个接口(token拦截, 2个业务流程,接口参数依赖校验)已经通过postman测试,记录部署服务器和windows,用于pytest接口自动化框架的接口测试对象
基于fastapi实现6个接口(token拦截, 2个业务流程,接口参数依赖校验)已经通过postman测试,记录部署服务器和windows,用于pytest接口自动化框架的接口测试对象
|
机器学习/深度学习 Python
【Python】fastapi框架之Web部署机器学习模型
【Python】fastapi框架之Web部署机器学习模型
|
存储 SQL 前端开发
FastAPI第三天---文件请求
FastAPI第三天---文件请求
165 0
FastAPI第三天---文件请求