【问题标题】:with FastAPI, is it possible to have default path parameters?使用 FastAPI,是否可以使用默认路径参数?
【发布时间】:2022-11-10 02:05:34
【问题描述】:

我的问题是,我怎样才能获得路径参数的默认值才能工作?

对于以下端点:

from FastAPI import Path as fPath

@app.get("/users/{code}")
async def get_user(code: str = fPath("hellomotto", regex=r'hello.*')):
    return {"code": code}

现在,如果我访问localhost:666/users/helloworld,它会给我一个很好的回应:

{"code": "helloworld"}

然而,如果我尝试去localhost:666/users/,它会给我一个{ "detail": "Not Found" }的回复

有没有办法让它默认返回{"code": "hellomotto"},以防用户没有输入localhost:666/users/hellomotto之类的东西

当然,我可以只为/users/ 设置一个端点,但我想我可以设置一个默认值...

编辑:也试过default="hellomoto" edit2:当我尝试使用查询参数时,它确实采用了默认值......

【问题讨论】:

    标签: python fastapi


    【解决方案1】:

    localhost:666/users/ 仅匹配 /users/,但它永远不会匹配 /users/{something}。这就是 FastAPI 返回 404 的原因。

    但是,以这种方式默认获取用户,对我来说听起来不像是一个好的 API 设计。通常,GET /something/ 将返回 something 的列表,而不是特定的默认元素。

    你可以做的是这样的:

    def _get_user(code: str):
        return {"code": code}
    
    @app.get("/users/{code}")
    async def get_user_by_code(code: str = Path(..., regex=r'hello.*')):
        return _get_user(code)
    
    @app.get("/users/default")
    async def get_user_by_default():
        return _get_user("hellomotto")
    
    

    如果您仍然想使用缺少的code 路径参数来执行此操作,您可以使用/users/ 而不是/users/default,但我仍然认为这不是一个好主意,因为它不够明确。除此之外,类似的东西应该有助于管理该默认用例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-12
      • 1970-01-01
      • 2013-06-26
      • 2010-12-16
      • 2022-01-08
      • 1970-01-01
      • 2016-07-03
      • 1970-01-01
      相关资源
      最近更新 更多