介绍
路径参数(Path Parameters)是构建 RESTful API 的核心组件之一
路径参数(Path Parameters):把变量写在URL路径里面,例如 /items/{item_id},{item_id} 就是路径参数。
应用场景
资源唯一标识符(RESTful 风格):当你需要获取、更新或删除某个数据时,将对象的 ID 放入路径中。
比如哔站的视频链接:https://www.bilibili.com/video/视频id
哔站王者荣耀链接:https://www.bilibili.com/video/BV1Q8uq6SESJ
基础用法
路径传入id,返回不同的视频
参数类型:默认参数类型是 字符串,URL传入任意类型的数据,几乎都能转为字符串。
from fastapi import FastAPI
app = FastAPI()
@app.get('/video/{id}')
async def get_video(id: str):
if id == '1':
video = {
'title': '王者荣耀视频',
}
elif id == '2':
video = {
'title': '吃鸡视频',
}
else:
video = {
'message': '视频不存在',
}
return video
测试
- 访问:
http://127.0.0.1:8000/video/1,返回{ "title": "王者荣耀视频" }
- 访问:
http://127.0.0.1:8000/video/3,返回{ "message": "视频不存在" }
类型声明
直接在函数参数写类型,FastAPI自动做 解析、校验
支持类型
str:默认类型,几乎可以接受任意类型参数int/items/123,转成int类型的123/items/12.3、/items/abc,校验报错422
float/price/99.99,转成float类型的99.99/price/100,转为100.0
booltrue、1,转为Truefalse、0,转为False
bytes:URL 传入 base64 编码字符串,自动解码为 bytes。uuid.UUID访问
/user/550e8400‑e29b‑41d4‑a71c‑95a26cf3d479正常转换格式不对直接报
422错误
例子
@app.get('/student/{id}')
async def get_student(id: int):
if id == 1:
student = {
'name': '李雷',
'age': 21,
}
elif id == 2:
student = {
'name': '韩梅梅',
'age': 21,
}
else:
student = {
'message': '没有此学号的学生',
}
return student
测试
访问
http://127.0.0.1:8000/student/1,显示下面内容:{ "name": "李雷", "age": 21 }访问
http://127.0.0.1:8000/student/abc,由于参数是abc,转int类型报错,显示如下:{ "detail": [ { "type": "int_parsing", "loc": [ "path", "id" ], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "abc" } ] }
路径参数顺序优先级
FastAPI 按从上到下匹配路由,精确路径要放在变量路径前面。
错误写法:
@app.get("/users/{user_id}")
async def get_user(user_id: int):
return {"user_id": user_id}
# 永远不会被命中,上面路由把 /users/me 匹配成 user_id="me"
@app.get("/users/me")
async def get_me():
return {"me": True}
正确写法
关键:精确路由放前面
@app.get("/users/me")
async def get_me():
return {"me": True}
@app.get("/users/{user_id}")
async def get_user(user_id: int):
return {"user_id": user_id}
多路径参数
一个url可以多个{},函数参数一一对应:
@app.get("/users/{user_id}/orders/{order_id}")
async def get_order(user_id: int, order_id: str):
return {"user_id": user_id, "order_id": order_id}
访问 /users/10/orders/ord_001。
OpenAPI自动文档
- SwaggerUI:
http://127.0.0.1:8000/docs - ReDoc:
http://127.0.0.1:8000/redoc
路径参数会自动出现在文档,支持在线调试;校验失败自动返回标准422 JSON错误响应。