在 FastAPI 中,有以下几种获取参数的方式:
从路径中获取参数(Path Parameters)
-
使用位置参数 :当定义接口函数时,将路径参数作为函数的参数即可。例如:
-
def read_item(item_id: int):
,其中item_id
是从路径中获取的参数,其类型被声明为int
,FastAPI 会自动对参数进行类型验证,确保传入的item_id
是整数。
-
-
使用
Path
函数 :通过from fastapi import Path
导入Path
函数,可以对路径参数进行更详细的配置,如设置参数的标题、描述、默认值、正则表达式约束等。例如:-
def read_item(item_id: int = Path(..., title="The ID of the item to get", gt=0))
,其中...
表示该参数是必需的,title
用于指定参数的标题,gt=0
表示该参数必须大于 0。
-
从查询字符串中获取参数(Query Parameters)
-
使用函数参数 :对于简单的查询参数,只需将参数名作为函数的参数即可,FastAPI 会自动从查询字符串中获取对应的值。例如:
-
def read_items(skip: int = 0, limit: int = 10):
,其中skip
和limit
是从查询字符串中获取的参数,默认值分别为 0 和 10 。
-
-
使用
Query
函数 :导入Query
函数后,可以对查询参数进行更详细的设置,如设置参数的默认值、是否必需、正则表达式、标题、描述等。例如:-
def read_items(q: str = Query(None, max_length=50))
,其中q
是查询参数,max_length=50
限制了该参数的最大长度为 50。
-
从请求体中获取参数(Request Body)
-
使用
Body
函数 :通过from fastapi import Body
导入Body
函数,将参数声明为从请求体中获取。例如:-
def create_item(item_id: int, name: str = Body(...), description: str = Body(None))
,其中name
是必需的请求体参数,description
是可选的请求体参数。
-
-
使用 Pydantic 模型 :使用 Pydantic 模型来定义请求体的结构和验证规则,然后在接口函数中将该模型作为参数类型。例如:
- 定义模型:
-
class Item(BaseModel):
name: str description: Optional[str] = None price: float tax: Optional[float] = None
-
- 在接口函数中使用模型:
-
def create_item(item: Item):
,FastAPI 会自动将请求体中的数据解析为Item
模型的实例。
-
- 定义模型:
从表单数据中获取参数(Form Data)
- 使用
Form
函数 :当需要处理表单数据时,可以使用Form
函数来声明参数。例如:-
def login(username: str = Form(...), password: str = Form(...))
,其中username
和password
是从表单数据中获取的参数。
-
从文件上传中获取参数(File Uploads)
- 使用
File
函数 :导入File
函数后,可以声明文件上传参数。例如:-
def upload_file(file: UploadFile = File(...))
,其中file
是一个UploadFile
对象,表示上传的文件。
-
从请求头或 cookie 中获取参数
- 使用
Header
或Cookie
函数 :通过Header
函数可以获取请求头中的参数,Cookie
函数用于获取 cookie 中的参数。例如:-
def read_items(user_agent: str = Header(None), ads_id: str = Cookie(None))
,其中user_agent
是从请求头中获取的User-Agent
参数,ads_id
是从 cookie 中获取的ads_id
参数。
-
这些方式可以单独使用,也可以组合使用,以满足不同的接口参数需求。在实际开发中,可以根据具体场景选择合适的参数获取方式。