【问题标题】:Python function for api callapi调用的python函数
【发布时间】:2022-10-14 05:42:36
【问题描述】:

我正在尝试使用 python 为几个 api 调用创建一个通用函数,如下所示-

import json
import requests

def api_call(url,payload,headers,request_type,auth):
    response = requests.request(request_type, url, payload, auth, headers)
    return response

虽然这在我直接在函数外部使用时有效,但当我调用函数并传递如下参数时,它会引发如下异常。

url = "https://api.xxxxxx"

payload = json.dumps({
  "Ids": ["12345","69845"],
  "startDate": "2022-01-01",
  "endDate": "2022-05-10"
})

headers = {
  'Accept': 'application/json',
  'Content-Type': 'application/json',
  'x-api-key': 'yyyyyyyy'}

request_type = 'post'
auth = None

resp = api_call(url=url, payload=payload, headers=headers, request_type=request_type, auth=auth)

我看到的错误如下 -

TypeError: request() takes 2 positional arguments but 5 were given

我该如何解决这个问题? 有人可以指导我。

谢谢!

【问题讨论】:

  • 您需要在您的 requests.request() 调用中提供像 data=payload, headers=headers) 这样的命名参数。
  • 你确定它在函数之外工作吗?如错误所示,只有前两个参数是位置参数。其他关键字。

标签: python python-3.x


【解决方案1】:

你必须像这样反转你的功能,

def api_call(url,payload,headers,request_type,auth):
    response = requests.request(request_type, url, payload=payload, headers=headers)
    return response

因为auth = None 你不需要通过它。

request(method, url, **kwargs):
  • methodurl 是位置参数,其余是关键字参数

【讨论】:

    猜你喜欢
    • 2017-04-06
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多