前言
请求体是客户端发送给 API 的数据,GET 请求不能发送请求体,
常见的发送请求体的请求方法:
- POST
- PUT
- DELETE
- PATCH
下面使用 POST 请求发送请求体,
定义请求体,需要使用 Pydantic 模型。
从 pydantic 中导入 BaseModel 模型
import BaseModel from pydantic
创建数据类型,声明数据模型为一个类,且该类继承 BaseModel
class Item(BaseModel):
name: str
description: Optional[str] = Field(
None, title="这是描述", max_length=300
)
price: float = Field(..., gt=0, description="价格大于0")
tax: Optional[float] = None
sales: list = []
"""
:param name: 书本名称
:param description: 描述
:param tax: 税费
:param sales: 销售地
"""
完整代码:
# coding:utf-8
from typing import Optional
from fastapi import Body, FastAPI
from pydantic import BaseModel, Field
import uvicorn
app = FastAPI()
class Item(BaseModel):
name: str
description: Optional[str] = Field(
None, title="这是描述", max_length=300
)
price: float = Field(..., gt=0, description="价格大于0")
tax: Optional[float] = None
sales: list = []
"""
:param name: 书本名称
:param description: 描述
:param tax: 税费
:param sales: 销售地
"""
@app.post("/book/{itemid}")
def post_items(itemid: int, item: Item = Body(..., embed=True)):
results = {"id": itemid, "item": item}
return results
if __name__ == '__main__':
uvicorn.run(app='demo003:app', host="127.0.0.1", port=8000, reload=True, debug=True)
使用 PostMan 进行接口调试: