FastAPI(4)- get 请求 – 路径参数 Path Parameters

什么是路径

  • 假设一个 url 是: //127.0.0.1:8080/items/abcd 
  • 那么路径 path 就是 /items/abcd 

 

路径参数

就是将路径上的某一部分变成参数,可通过请求传递,然后 FastAPI 解析

 

最简单的栗子

import uvicorn
from fastapi import FastAPI

app = FastAPI()


# 路径参数 item_id
@app.get("/items/{item_id}")
async def read_item(item_id):
    return {"item_id": item_id}


if __name__ == '__main__':
    uvicorn.run(app="2_get:app", host="127.0.0.1", port=8080, reload=True, debug=True)

 

postman 请求结果

 

限定类型的路径参数

# 指定类型的路径参数
@app.get("/items/{item_id}/article/{num}")
async def path_test(item_id: str, num: int):
    return {"item_id": item_id, "num": num}

多个路径参数,且有指定类型

 

正确传参的请求结果

123 传进来的时候是字符串,但 FastAPI 会自动解析转换成 int,如果转换失败就会报错

 

num 不传 int 的请求结果

 

友好的错误提示类型不对

 

Swagger 接口文档的显示效果

 

路径函数顺序问题

@app.get("/users/me")
async def read_user_me():
    return {"user_id": "the current user"}


@app.get("/users/{user_id}")
async def read_user(user_id: str):
    return {"user_id": user_id}

/users/{user_id} 路径是包含 /users/me 的

当想匹配到固定路径时,需要将固定路径函数放在路径参数函数前面

 

postman 请求结果

 

将两个函数顺序换过来

@app.get("/users/{user_id}")
async def read_user(user_id: str):
    return {"user_id": user_id}

# 顺序问题
@app.get("/users/me")
async def read_user_me():
    return {"user_id": "the current user"

这样就无法匹配到固定路径 /users/me 的函数了

 

路径转换器

前言

  • 当你有一个路径是 /files/{file_path} ,但是不确定 file_path 到底会取什么值,并不是固定的长度,可能是 /files/home/johndoe/myfile.txt 也可能是 /files/test/myfile.txt ,那怎么办呢?
  • 路径转换器出来啦!

 

实际栗子

# 路径转换器
@app.get("/files/{file_path:path}")
async def read_file(file_path: str):
    return {"file_path": file_path}

 

postman 请求结果

 

枚举类型的路径参数

# 导入枚举类
from enum import Enum

# 自定义枚举类
class ModelName(Enum):
    polo = "polo"
    yy = "yy"
    test = "test"


@app.get("/models/{model_name}")
# 类型限定为枚举类
async def get_model(model_name: ModelName):
    # 取枚举值方式一
    if model_name == ModelName.polo:
        return {"model_name": model_name, "message": "oh!!polo!!"}

    # 取枚举值方式二
    if model_name.value == "yy":
        return {"model_name": model_name, "message": "god!!yy"}

    return {"model_name": model_name, "message": "巴拉巴拉"}

 

参数传枚举值的请求结果

 

参数传非枚举值的请求结果

错误提示传的参数值并不是枚举类中的值

 

重点:路径参数可以不传吗?

先说答案,不行!路径参数是必传参数

 

实际栗子

# 路径参数 item_id
@app.get("/items/{item_id}")
async def read_item(item_id):
    return {"item_id": item_id}

 

假设不传 item_id

 

总结

路径参数是请求路径的一部分,如果不传,请求的是另一个路径,如果不存在就会 404