文章目录
1. 约束限制
2. 必须参数
3. 查询参数列表 / 多个值
4. 声明更多元数据
5. 别名参数
6. 弃用参数
7. Path 路径参数
8. 按需对参数排序
learn from https://fastapi.tiangolo.com/zh/tutorial/query-params-str-validations/
1. 约束限制
from typing import Optional from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(q: Optional[str] = Query(None, max_length=50)): res = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: res.update({"q":q}) return res
Query(None, max_length=50)
显示声明为查询参数,默认为 None, 最大长度50
- 更多限制
Query(None, min_length=3, max_length=50)
- 正则限制
Query(None, min_length=3, max_length=50, regex="^fixedquery")
, 以 ^ 后面的字符开头
注意 None 是默认值,也可以是其它默认值,改参数是可选的
2. 必须参数
将 默认值替换成 ...
q: Optional[str] = Query(..., min_length=3, max_length=50, regex="^fixedquery$")
3. 查询参数列表 / 多个值
添加 List[str],q: Optional[List[str]] = Query(None)
http://127.0.0.1:8000/items/?q=123456&q=7890&q=hahha
在没有任何给定值时,赋予默认值 q: Optional[List[str]] = Query(["mike","jason"]
4. 声明更多元数据
- 添加
title
,description
async def read_items(q: list = Query(["mike","jason"], title="查询字符串", description="查询匹配的item", ) ): res = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: res.update({"q":q}) return res
5. 别名参数
你需要在浏览器里使用 参数 item-good,但是 python 不支持 - 作为变量名
q: Optional[str] = Query(None, alias = "item-good")
6. 弃用参数
将参数 deprecated=True 传入 Query
7. Path 路径参数
from fastapi import Path @app.get("/items/{item_id}") async def read_items(item_id:int = Path(..., title="the id of the item"), q : Optional[str] = Query(None, alias="item-query")): results = {"item_id": item_id} if q: results.update({"q": q}) return results
限制大小 item_id:int = Path(..., title="the id of the item", ge=23, le=24),[23.0, 24.0] 之间的 int
路径参数总是 必需的
8. 按需对参数排序
fastapi 会自动根据 参数的名称、类型和默认值声明(Query、Path 等)来检测参数
from fastapi import Path @app.get("/items/{item_id}") async def read_items( q: str, item_id: int = Path(..., title="The ID of the item to get, hha", description="my description") ): results = {"item_id": item_id} if q: results.update({"q": q}) return results
@app.get("/items/{item_id}") async def read_items( q:str, item_id: int = Path(..., title="The ID of the item to get") ): results = {"item_id": item_id} if q: results.update({"q": q}) return results
对上面的代码,参数 q,item_id 的顺序如果调换了,会报错
item_id: int = Path(..., title="The ID of the item to get"), q: str ^ SyntaxError: non-default argument follows default argument
加入第一个参数 *
,表示让后面的所有参数作为键值对参数
@app.get("/items/{item_id}") async def read_items( *, item_id: int = Path(..., title="The ID of the item to get"), q:str ): results = {"item_id": item_id} if q: results.update({"q": q}) return results