路径参数
函数参数中出现在路径操作装饰器中,该参数称为路径参数
app = FastAPI()@app.get("/info/{id}")async def info(id: str):return {"id": id}# 以上参数id称为路径参数
路径参数更多校验-Path
导入Path可为路径参数声明元数据和校验
from fastapi import FastAPI, Path"""路径参数校验Path"""# 声明元数据@app.get("/items/{item_id}/{id}")def read_item(item_id: str = Path(..., title="这是元数据title", description="这是描述", max_length=10),id: int = Path(..., ge=0, le=10)):return {"item_id": item_id}
查询参数
函数参数中没有出现在路径操作装饰器中的参数,称为查询参数
@app.get("/info_1")async def info_1(id: str):return {"id": id}"""curl --location --request GET 'http://127.0.0.1:8087/info_1?id=1' \--data-raw ''{"id": "1"}"""# 以上参数id为查询参数
查询参数更多校验-Query
设置默认值
from fastapi import FastAPI, Query# 设置默认值@app.get('/read_items')# 设置q参数默认值为testasync def read_items(q: Optional[str] = Query("test", max_length=50)):results = {"item_id": "12345"}if q:results.update({"q": q})print("results:", results)return results
声明是否必填参数
通过Query显性的声明一个值是否必填,可通过…作为第一个参数值
# 声明参数必填@app.get("/read_items")async def read_items(q: str = Query(..., max_length=30)):return {"q": q}"""q参数不填时提示信息如下:{"detail": [{"loc": ["query","q"],"msg": "field required","type": "value_error.missing"}]}"""
设置参数限制
min_length:限制参数最小字符长度 max_length:限制参数最大字符长度 regex:参数匹配正则表达式
# 参数限制@app.get("/read_items")async def read_items(q: Optional[str] = Query(None, min_length=3, max_length=50, regex="^fixedquery$")):return {"q": q}
声明参数元数据
title:参数标题 description:参数描述
# 添加参数元数据@app.get("/read_items")async def read_items(q: Optional[str] = Query(None,title="请求参数title",description="请求参数描述文本",min_length=3,)):return {"q": q}
别名参数&弃用参数
有时候查询参数为item-id,但是该参数在python是非法的,这时候可以用上alias声明一个别名
# 设置参数别名@app.get("/read_items/")async def read_items(q: str = Query(None, alias="item-id")):return {"q": q}"""请求URL:http://127.0.0.1:8087/read_items?item-id=zaygee"""
请求体
pydantic模型请求体&查询参数&路径参数
pydantic模型使用
- item.dict():返回模型字段和值的字典
- **item.dict(): 字典解包 ```python class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None
@app.put(“/items/{item_id}”) async def create_item(item_id: int, item: Item, q: Optional[str] = None):
# {'name': 'zayee', 'description': 'dddfsdfdsf', 'price': 10.0, 'tax': 110.0} <class 'dict'> zayeeprint(item.dict(), type(item.dict()), item.dict().get("name", ""))# result: {'item_id': 3243, 'name': 'zayee', 'description': 'dddfsdfdsf', 'price': 10.0, 'tax': 110.0}result = {"item_id": item_id, **item.dict()}...
<a name="lRUtC"></a>#### 多个参数中的单一参数-Body> 导入Body,可起到扩充已定义模型的作用```pythonfrom fastapi import Bodyclass Item(BaseModel):name: strdescription: Optional[str] = Noneprice: floattax: Optional[float] = Noneclass User(BaseModel):username: strfull_name: Optional[str] = None@app.put("/items/{item_id}")async def update_item(item_id: int, item: Item, user: User, importance: int = Body(...)):results = {"item_id": item_id, "item": item, "user": user, "importance": importance}return results@app.post("/items_2")async def get_item(item_id: int, data: str = Body(...), items: str= Body(...)):return {"item_id": item_id, "data": data, "items": items}
嵌入单个请求体参数-embed=True
如果你希望item键的值为包含模型的json,可以设置Body的参数embed=True
"""嵌入单个请求体参数request:{"items": {"name": "string","description": "string","price": 0,"tax": 0}}"""@app.post("/items_3")async def get_item_2(items: Item = Body(..., embed=True)):return {"items": items}
pydantic模型增加元数据&属性校验-Field
from pydantic import Field"""pydantic模型声明元数据&校验 -- Field"""class ItemField(BaseModel):name: str = Field("zaygee", title="名称", description="这是描述", max_length=100)description: Optional[str] = Noneprice: float = Field(..., ge=0.0, le=100.0)tax: Optional[float] = None@app.post("/items-4")async def get_items_4(items: ItemField):return {"items": items}
多层嵌套模型
class Image(BaseModel):url: HttpUrlname: strclass Item5(BaseModel):name: strdescription: Optional[str] = Noneprice: floattax: Optional[float] = Nonetags: Set[str] = set()images: Optional[List[Image]] = None@app.put("/items5/{item_id}")async def update_item(item_id: int, item: Item5):results = {"item_id": item_id, "item": item}return results"""{"name": "string","description": "string","price": 0,"tax": 0,"tags": [],"images": [{"url": "string","name": "string"}]}"""
接收表单数据
接收的不是json,而是表单字段,要使用Form
条件: 安装python-multipart包
from fastapi import Form"""表单数据-Form"""@app.post("/item12")async def item12(username: str = Form(...), pw: str= Form(...)):return {"username": username}
为参数&请求体添加示例
针对请求体或者请求参数为接口在接口文档中添加请求示例
pydantic 的schema_extra
class Item(BaseModel):name: strdescription: Optional[str] = Noneprice: floattax: Optional[float] = Noneclass Config:schema_extra = {"example": {"name": "Foo","description": "A very nice Item","price": 35.4,"tax": 3.2,}}@app.put("/items/{item_id}")async def update_item(item_id: int, item: Item):results = {"item_id": item_id, "item": item}return results
Field
class Item(BaseModel):name: str = Field(..., example="Foo")description: Optional[str] = Field(None, example="A very nice Item")price: float = Field(..., example=35.4)tax: Optional[float] = Field(None, example=3.2)
Body
@app.put("/items/{item_id}")async def update_item(item_id: int,item: Item = Body(...,example={"name": "Foo","description": "A very nice Item","price": 35.4,"tax": 3.2,},),):results = {"item_id": item_id, "item": item}return results
Cookie 参数 && Header参数
设置Header参数时,可通过设置convert_underscores=False,来禁止下划线的自动转换
from fastapi import Cookie, Header@app.get("/items8")async def get_items8(asd_id: Optional[str] = Cookie(None),user_agent: Optional[str] = Header(None, convert_underscores=True)):"""声明Cookie 参数 && Header参数"""return "声明Cookie 参数 && Header参数"
总结
- 如果在路径中也声明了该参数,它将被用作路径参数。
- 如果参数属于单一类型(比如 int、float、str、bool 等)它将被解释为查询参数。
- 如果参数的类型被声明为一个 Pydantic 模型,它将被解释为请求体
