引言:
最近工作中有机会接触FastAPI这个框架,所以就把官方文档看了一遍,对框架的各个特性及使用方法做了总结,会逐步的发出来,希望对您有用。
如果您之前接触过python的其他框架,看起来会非常简单和顺畅,其实就是很简单。
【上一篇】:【FastAPI基础】2、路径参数(基于python36+类型提示)
【下一篇】:【FastAPI基础】4、数据请求体
【FastAPI搭建好的产品框架源码,直接上手】:【FastAPI搭建好的产品架构】,直接上手
1、声明不属于路径参数的其他函数参数时,它们将被自动解释为"查询字符串"参数
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
2、默认值
由于查询参数不是路径的固定部分,因此它们可以是可选的,并且可以有默认值。
在上面的示例中,它们具有 skip=0 和 limit=10 的默认值。
3、可选参数 Optional
通过同样的方式,你可以将它们的默认值设置为 None 来声明可选查询参数:
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: str, q: Optional[str] = None):
if q:
return {"item_id": item_id, "q": q}
return {"item_id": item_id}
在这个例子中,函数参数 q 将是可选的,并且默认值为 None。
还要注意的是,FastAPI 足够聪明,能够分辨出参数 item_id 是路径参数而 q 不是,因此 q 是一个查询参数。
4、多个路径和查询参数
你可以同时声明多个路径参数和查询参数,FastAPI 能够识别它们。而且你不需要以任何特定的顺序来声明。它们将通过名称被检测到:
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/{user_id}/items/{item_id}")
async def read_user_item(
user_id: int, item_id: str, q: Optional[str] = None, short: bool = False
):
item = {"item_id": item_id, "owner_id": user_id}
if q:
item.update({"q": q})
if not short:
item.update(
{"description": "This is an amazing item that has a long description"}
)
return item
5、必需查询参数
当你为非路径参数声明了默认值时(目前而言,我们所知道的仅有查询参数),则该参数不是必需的。
如果你不想添加一个特定的值,而只是想使该参数成为可选的,则将默认值设置为 None。
但当你想让一个查询参数成为必需的,不声明任何默认值就可以:
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_user_item(item_id: str, needy: str):
item = {"item_id": item_id, "needy": needy}
return item
这里的查询参数 needy 是类型为 str 的必需查询参数。