2.FastAPI 中的路由与路径操作
文章目录
- 什么是路由?以及怎么通过路由定义不同路径的get请求
- 查询参数
- 路径参数
- 请求体参数
什么是路由?以及怎么通过路由定义不同路径的get请求
- 在 FastAPI 中,路由的定义是通过装饰器来实现的,@app.get(“/”) 这个装饰器告诉 FastAPI 当接收到对根路径的 GET 请求时,要执行下面的 read_root 函数。
from fastapi import FastAPI
# 创建一个fastapi应用实例
app = FastAPI()
# 对应根路劲的get请求
@app.get("/")
def read_root():
return {"message":"你好"}
# 对于"/index"路径的get请求
@app.get("/index")
def get_index():
return {"message":"root"}
查询参数
-
/items/?skip=5&limit=20
- 路径?后面的就是查询参数,键值对表示,&连接不同的查询参数;
- 表示查询参数skip的值为5,limit的值为20
-
可选查询参数
- 如果某个查询参数是可选的,可以为其设置默认值
None
:
- 如果某个查询参数是可选的,可以为其设置默认值
-
参数验证
- FastAPI 自动支持参数验证。例如,如果参数类型是
int
,但用户传递了非整数值,FastAPI 会返回一个错误响应。
- FastAPI 自动支持参数验证。例如,如果参数类型是
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10, item_id:int=None):
return {"skip": skip, "limit": limit}
路径参数
- /index/{name}
- name就是路径参数
- 默认路径参数
- 如下面例子中的get_index函数,会绑定两个路由;
from fastapi import FastAPI
# 创建一个fastapi应用实例
app = FastAPI()
# 对应根路劲的get请求
@app.get("/")
def read_root():
return {"message": "你好"}
# 这两个装饰器都指向同一个处理函数 get_index。
# 如果用户访问 /index(没有提供 name 参数),函数会使用默认值 "xu.henry"。
# 如果用户访问 /index/{name}(提供了 name 参数),函数会使用用户传递的值。
@app.get("/index")
@app.get("/index/{name}")
def get_index(name: str = "xu.henry"):
return {"name": name}
请求体参数
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
# 定义请求体的数据模型
class Item(BaseModel):
name: str
price: float
is_offer: bool = None
# 使用请求体参数的路由
@app.post("/items/")
async def create_item(item: Item):
return item