FastAPI-6-请求体


当你需要将数据从客户端(例如浏览器)发送给 API 时,你将其作为「请求体」发送。

请求体是客户端发送给 API 的数据。响应体是 API 发送给客户端的数据。

你不能使用 GET 操作(HTTP 方法)发送请求体。

要发送数据,你必须使用下列方法之一:POST(较常见)、PUTDELETE 或 PATCH

我们使用 Pydantic 模型来声明请求体,并能够获得它们所具有的所有能力和优点。

from typing import Optional

from fastapi import FastAPI
from pydantic import BaseModel


class Item(BaseModel):                   #  创了一个模板接受四个参数
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None


app = FastAPI()


@app.post("/items/")
async def create_item(item: Item):   # 这里声明了item的参数要符合Item模板,使用postman发送请求的时候传的json参数就是{'name':'fan','price':12.8,'tax':0.95}  description 和 tax 是可选项
 return item

仅仅使用了 Python 类型声明,FastAPI 将会:

  • 将请求体作为 JSON 读取。
  • 转换为相应的类型(在需要时)。
  • 校验数据。
    • 如果数据无效,将返回一条清晰易读的错误信息,指出不正确数据的确切位置和内容。
  • 将接收的数据赋值到参数 item 中。
    • 由于你已经在函数中将它声明为 Item 类型,你还将获得对于所有属性及其类型的一切编辑器支持(代码补全等)。
  • 为你的模型生成 JSON 模式 定义,你还可以在其他任何对你的项目有意义的地方使用它们。
  • 这些模式将成为生成的 OpenAPI 模式的一部分,并且被自动化文档 

    你可以同时声明路径参数和请求体。

    FastAPI 将识别出与路径参数匹配的函数参数应从路径中获取,而声明为 Pydantic 模型的函数参数应从请求体中获取

    from typing import Optional
    
    from fastapi import FastAPI
    from pydantic import BaseModel
    
    
    class Item(BaseModel):
        name: str
        description: Optional[str] = None
        price: float
        tax: Optional[float] = None
    
    
    app = FastAPI()
    
    
    @app.put("/items/{item_id}")
    async def create_item(item_id: int, item: Item):
        return {"item_id": item_id, **item.dict()}

    请求体 + 路径参数 + 查询参数?

    你还可以同时声明请求体路径参数查询参数

    FastAPI 会识别它们中的每一个,并从正确的位置获取数据

    from typing import Optional
    
    from fastapi import FastAPI
    from pydantic import BaseModel
    
    
    class Item(BaseModel):
        name: str
        description: Optional[str] = None
        price: float
        tax: Optional[float] = None
    
    
    app = FastAPI()
    
    
    @app.put("/items/{item_id}")
    async def create_item(item_id: int, item: Item, q: Optional[str] = None):  # item_id 为路径参数,item为请求体,q为查询参数
        result = {"item_id": item_id, **item.dict()}
        if q:
            result.update({"q": q})
        return result

    学习Pydantic:https://www.cnblogs.com/tarzen213/p/15845994.html