You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

API筛选器URL为何用斜杠而非等号?FastAPI路由配置疑问

问题与解决方案

当前你的API通过路径参数/person/{id}可正常返回记录,但期望URL格式为http://fastapi.localhost:8008/person=2,以下是两种实现方式:

方式一:直接匹配带等号的路径(非标准格式)

修改路由定义,将路径改为/person={id},FastAPI会自动捕获等号后的数值作为id参数:

@app.get("/person={id}", tags=["API Endpoint"])
async def get_persons(id: int | None = None, person: str | None = None, yesno: str | None = None):
    if id is not None:
        return await Person.objects.get(pk=id)
    # 可补充person、yesno参数的查询逻辑

此时访问http://fastapi.localhost:8008/person=2即可获取对应ID的记录。

方式二:使用标准查询参数(推荐)

如果你的实际需求是通过键值对传递参数,更规范的做法是使用查询参数,此时路由改为/person,URL格式为http://fastapi.localhost:8008/person?id=2:

@app.get("/person", tags=["API Endpoint"])
async def get_persons(id: int | None = None, person: str | None = None, yesno: str | None = None):
    if id is not None:
        return await Person.objects.get(pk=id)
    # 可补充person、yesno参数的查询逻辑

这种格式符合HTTP规范,更易于理解和维护,也支持同时传递多个参数(如/person?id=2&yesno=yes)。

注意事项

  • 方式一的/person=2格式不属于RESTful标准路径格式,仅在特定业务场景下使用;
  • 确保Person模型的查询逻辑正确,当id为None时需补充对应的处理逻辑(如返回所有记录或根据其他参数过滤)。

内容的提问来源于stack exchange,提问作者IamTrying

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 06:31:20