额外校验
使用Query可以对查询参数添加校验
from typing import Unionfrom fastapi import FastAPI, Queryapp = FastAPI()@app.get("/items/")
async def read_items(q: Union[str, None] = Query(default=None, max_length=50)):results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}if q:results.update({"q": q})return results
default:默认值
max_length:最大长度
min_length:最小长度
pattern:正则表达式
声明为必须参数
当使用Query声明一个查询参数为必须参数时,只用不声明默认值就行,也就是default不传
from fastapi import FastAPI, Queryapp = FastAPI()@app.get("/items/")
async def read_items(q: str = Query(min_length=3)):results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}if q:results.update({"q": q})return results
使用省略号(...)声明必填参数
from fastapi import FastAPI, Queryapp = FastAPI()@app.get("/items/")
async def read_items(q: str = Query(default=..., min_length=3)):results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}if q:results.update({"q": q})return results
使用Pydantic中的Required代替省略号
from fastapi import FastAPI, Query
from pydantic import Requiredapp = FastAPI()@app.get("/items/")
async def read_items(q: str = Query(default=Required, min_length=3)):results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}if q:results.update({"q": q})return results
使用None声明必须参数
from typing import Unionfrom fastapi import FastAPI, Queryapp = FastAPI()@app.get("/items/")
async def read_items(q: Union[str, None] = Query(default=..., min_length=3)):results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}if q:results.update({"q": q})return results
声明None是个有效类型,这样将强制客户端传一个值。即使这个值是None
查询参数列表,多个值
使用Query显式地定义查询参数时,还可以声明它去接收一组值,或换句话来说,接收多个值。
例如,要声明一个可在 URL 中出现多次的查询参数
from typing import List, Unionfrom fastapi import FastAPI, Queryapp = FastAPI()@app.get("/items/")
async def read_items(q: Union[List[str], None] = Query(default=None)):query_items = {"q": q}return query_items
http://localhost:8000/items/?q=foo&q=bar
要声明类型为List的查询参数,需要显示使用Query,否则该参数将被当做请求体解析
具有默认值的查询参数列表/多个值
from typing import Listfrom fastapi import FastAPI, Queryapp = FastAPI()@app.get("/items/")
async def read_items(q: List[str] = Query(default=["foo", "bar"])):query_items = {"q": q}return query_items
http://localhost:8000/items/
更多元数据
from typing import Unionfrom fastapi import FastAPI, Queryapp = FastAPI()@app.get("/items/")
async def read_items(q: Union[str, None] = Query(default=None,alias="item-query",title="Query string143242542",description="Query string for the items to search in the database that have a good match",min_length=3,max_length=50,pattern="^fixedquery$",deprecated=True,),
):results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}if q:results.update({"q": q})return results
alias:参数别名
title:不知道啥效果,没试出来
description:自动文档上的参数描述
deprecated:True时自动文档提示弃用参数