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

如何让FastAPI的OpenAPI文档展示未命名的多查询字符串参数?

解决FastAPI OpenAPI界面展示多查询参数的问题

你不需要用单个qs参数来接收所有查询字符串,FastAPI原生支持直接定义多个查询参数,同时会自动在OpenAPI文档中展示这些独立的参数输入框。

固定查询参数的实现方式

  • 直接在接口函数中定义需要的查询参数,比如amount__gt和start_date__lt,可设置为可选参数(结合Optional类型)
  • FastAPI会自动解析这些参数为独立的查询字符串元素,同时在OpenAPI文档生成对应的输入项

示例代码:

from fastapi import FastAPI, Query
from typing import Optional
from datetime import date

app = FastAPI()

@app.get("/your-resource/")
async def get_resource(
    amount__gt: Optional[float] = Query(None, description="金额大于指定值"),
    start_date__lt: Optional[date] = Query(None, description="开始日期早于指定日期")
):
    # 此处编写业务逻辑
    return {"amount__gt": amount__gt, "start_date__lt": start_date__lt}

效果说明

  • 配置完成后,访问默认的/docs路径查看OpenAPI文档,会看到两个独立的查询参数输入框,分别对应amount__gt和start_date__lt
  • 在文档中输入值调用接口时,生成的查询字符串会是amount__gt=1000&start_date__lt=2023-05-10,和PostMan调用的效果完全一致

动态查询参数的处理(参数不固定时)

如果需要支持不确定名称的动态查询参数,可以通过Request对象直接获取所有查询参数:

from fastapi import FastAPI, Request

app = FastAPI()

@app.get("/your-resource/")
async def get_resource(request: Request):
    query_params = request.query_params
    # 根据需要提取具体参数
    amount_gt = query_params.get("amount__gt")
    start_date_lt = query_params.get("start_date__lt")
    # 编写业务逻辑
    return {"received_query_params": dict(query_params)}

注意:这种方式下OpenAPI文档不会自动生成参数输入框,若需要在文档中展示,需手动添加OpenAPI扩展描述参数;如果参数是固定的,优先使用第一种方法,更符合REST规范且文档展示更友好。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 09:15:33