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参数核心原理
参数风格差异
- 原脚本采用的是OData规范的
$filter参数,这类参数通过表达式筛选资源,常见于微软系REST API。 - 目标API要求的是普通键值对参数,即直接将参数名和对应值作为URL查询串的键值对,格式为
key1=value1&key2=value2。
- 原脚本采用的是OData规范的
httpx的参数处理逻辑
- 向
httpx.get()的params参数传入字典时,httpx会自动完成URL编码(比如转义特殊字符、空格),并拼接成标准的查询串,无需手动调用urlencode拼接。 - 原脚本中
url_with_params变量属于冗余代码,httpx会自动生成带参数的完整URL。
- 向
参数冗余清理
- 如果目标API不需要
format参数,直接删除对应的Query参数定义和params字典中的键即可,避免传递无效参数导致接口报错。
- 如果目标API不需要
内容的提问来源于stack exchange,提问作者Laupie
相关产品推荐
相关产品推荐

