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

Python编写通用API调用函数遇TypeError错误,求解决方案

问题原因与解决方案

错误原因

requests.request()的函数签名为requests.request(method, url, **kwargs),仅前两个参数(请求方法、URL)支持位置传递,其余参数(如请求体、认证信息、请求头)必须以关键字参数形式传入。你之前的封装函数直接将payload、auth、headers作为位置参数传递,违反了该函数的参数规则,因此触发TypeError。

修正后的代码

方案1:适配已JSON序列化的payload

如果坚持提前用json.dumps()处理payload,需将其对应到data关键字参数:

import json
import requests

def api_call(url, payload, headers, request_type, auth):
    # 用关键字参数传递所有非method/url的参数
    response = requests.request(
        method=request_type,
        url=url,
        data=payload,
        auth=auth,
        headers=headers
    )
    return response

方案2:简化payload处理(推荐)

直接传入Python字典,让requests自动完成JSON序列化,无需手动调用json.dumps():

import requests

def api_call(url, payload, headers, request_type, auth):
    response = requests.request(
        method=request_type,
        url=url,
        json=payload,  # 直接传字典,requests自动处理序列化
        auth=auth,
        headers=headers
    )
    return response

# 调用时的payload无需json.dumps
payload = {
  "Ids": ["12345","69845"],
  "startDate": "2022-01-01",
  "endDate": "2022-05-10"
}

验证调用

修正函数后,原调用代码即可正常运行,不会再抛出参数数量错误的异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 18:05:33