跳转至

各种参数

参数类型

HTTP请求中,常见的参数包括

  • 路径参数
  • 查询参数
  • 请求体参数

路径参数

路径参数分两种,一种是固定的,一种是可变的

  • 固定的路径参数,装饰器中包裹的路径中的路径中没有可变部分
@app.get("/")
async def root():
    return {"Hello": "World"}
  • 可变的路径参数,在装饰器中需要有变量名,在接口函数中需要将此变量作为形参
@app.get("/hello/{hello_id}")
async def hello(hello_id: int):
    return {"hello_id": hello_id}

查询参数

查询参数存在于URL中,fastapi认为,除了可变路径参数/请求体参数之外,剩下的都是查询参数

# 例子1
@app.get("/test")
async def query(q: Union[str, None] = None):
    return {"q": q}


# 例子2
@app.get("/double/{uid}")
async def double(uid: int, q: str):
    return {"uid": uid, "q": q}

请求体参数

上面都是get请求,只有路径参数和查询参数。而post/put等请求中,往往有请求体,如何识别这些内容?fastapi认为,函数的参数中,如果有参数的类型是继承自BaseModel的,那就是请求体内容。

class Info(BaseModel):
    name: str
    description: Optional[str] = None
    price: float


@app.post("/body-test/")
async def body(info: Info):
    return info