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

Python对接现有API时URL格式适配问题及脚本修改方案

修改后的脚本

直接调整params字典结构,去掉OData风格的$filter包装,将参数直接作为顶级键值对传入;如果目标API不需要format参数,直接删除对应逻辑即可:

@app.get("/dirdetails/fetchdetails")
async def custom_operation5(
    Application: str = Query("CTV", description="Application"),
    DocumentName: str = Query("G76410", description="DocumentName"),
    FileID: str = Query("FOL43000000015861EXT47000000001577", description="FileID"),
    # 若目标API不需要format参数,直接删除此行
    # format: str = Query("json", description="Response format")
):
    path="/dirdetails/fetchdetails"

    url = f"{settings.api_baseurl}{settings.api_env}{path}"

    # 直接将参数以普通键值对形式传入,无需$filter包装
    params = {
        "Application": Application,
        "DocumentName": DocumentName,
        "FileID": FileID
        # 若目标API需要format参数,保留此行;否则删除
        # "format": format
    }

    try:
        async with httpx.AsyncClient() as client:
            response = await client.get(url, params=params, auth=auth, headers=common_headers)
            response.raise_for_status()
            return response.json()
    
    except httpx.HTTPError as e:
        return {"error": str(e)}
    except Exception as e:
        return {"error": "An unexpected error occurred."}

URL参数核心原理

  1. 参数风格差异

    • 原脚本采用的是OData规范的$filter参数,这类参数通过表达式筛选资源,常见于微软系REST API。
    • 目标API要求的是普通键值对参数,即直接将参数名和对应值作为URL查询串的键值对,格式为key1=value1&key2=value2。
  2. httpx的参数处理逻辑

    • 向httpx.get()的params参数传入字典时,httpx会自动完成URL编码(比如转义特殊字符、空格),并拼接成标准的查询串,无需手动调用urlencode拼接。
    • 原脚本中url_with_params变量属于冗余代码,httpx会自动生成带参数的完整URL。
  3. 参数冗余清理

    • 如果目标API不需要format参数,直接删除对应的Query参数定义和params字典中的键即可,避免传递无效参数导致接口报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 00:05:02