当你声明函数参数的时候,如果参数并不是来自路径参数中,那么将被自动视为查询参数。
from fastapi import FastAPI
app = FastAPI()
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
return fake_items_db[skip : skip + limit]
这个查询是一个键值对,在url中的?之后,并且使用&符号隔开。
http://127.0.0.1:8000/items/?skip=0&limit=10
可选参数
当你把查询参数默认值设置为None的时候,这个参数就是可选参数。
…
async def read_item(item_id: str, q: str = None):
…
多路径参数和查询参数
…
@app.get("/users/{user_id}/items/{item_id}")
async def read_user_item(
user_id: int, item_id: str, q: str = None, short: bool = False
):
…
必须的查询参数
如果查询参数为必须的,可以在声明的时候不添加默认值
…
@app.get("/items/{item_id}")
async def read_user_item(item_id: str, needy: str):
…
warnning:
如果在声明参数为可选参数的时候,程序报错,
limit:str=None
Incompatible types in assignment (expression has type “None”, variable has type “int”)
可以使用Optional告诉程序变量的值可以为None
from typing import Optional
…
async def read_user_item(item_id:str,limit:Optional[int]=None):
…
本文深入探讨了FastAPI框架中如何使用查询参数,包括必填、可选参数的定义方式,以及如何处理多个路径和查询参数。同时,文章还讲解了如何通过Optional类型注解来正确处理可选参数。
1083

被折叠的 条评论
为什么被折叠?



